Last active
January 7, 2016 03:03
-
-
Save kaisellgren/11393718 to your computer and use it in GitHub Desktop.
Academic Scala implementations of Functional Reactive Programming -- different Signal[A] and foldp[A, B] implementations as examples
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Haskell Signal foldp implementation. | |
| class Signal[A](initial: A) { | |
| // Listener :: A => Unit or however you annotate it in Haskell.. | |
| type Listener = Function[A, Unit] | |
| val value = Ref(initial) | |
| val listeners = Ref(Seq[Listener]()) | |
| def set(newValue: A): Unit = { | |
| // Atomically change the value, blocks the thread, but a not an issue since it's a simple operation. | |
| // Finally return the current state/set of listeners. | |
| atomic { implicit txn => | |
| value() = newValue | |
| listeners() | |
| }.foreach(_(newValue)) | |
| } | |
| def get: A = atomic { implicit txn => | |
| value() | |
| } | |
| def listen(listener: Listener): Unit = atomic { implicit txn => | |
| listeners() = listeners() :+ listener | |
| } | |
| } | |
| object Foo extends App { | |
| val slot = new Signal(0) | |
| slot.listen({ value => | |
| println(value) // hooray! | |
| }) | |
| slot.set(5) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment