Created
December 5, 2019 15:56
-
-
Save bkyrlach/2236bc926b503b206a02c80a8b51831e to your computer and use it in GitHub Desktop.
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
| object Program { | |
| def main(args: Array[String]): Unit = { | |
| val pgm1 = FrontEnd.clickMe | |
| val pgm2 = FrontEnd.clickMe2 | |
| val init = AppState(-4) | |
| val s1 = App.eval(pgm1, init) | |
| println(s1) | |
| val s2 = App.eval(pgm2, init) | |
| println(s2) | |
| } | |
| } | |
| sealed trait AppAction | |
| case object Noop extends AppAction | |
| case class AndThen(first: AppAction, second: AppAction) extends AppAction | |
| case object Increment extends AppAction | |
| case class Add(n: Int) extends AppAction | |
| case class AppState(count: Int) | |
| object App { | |
| def eval(action: AppAction, env: AppState): AppState = action match { | |
| case Noop => env | |
| case AndThen(a1, a2) => | |
| val stateAfterA1 = eval(a1, env) | |
| val stateAfterA2 = eval(a2, stateAfterA1) | |
| stateAfterA2 | |
| case Increment => env.copy(count = env.count + 1) | |
| case Add(n) => env.copy(count = env.count + n) | |
| } | |
| def buildProgram(xs: AppAction*): AppAction = xs.foldLeft[AppAction](Noop) { (b,a) => AndThen(b, a) } | |
| } | |
| object FrontEnd { | |
| def clickMe: AppAction = App.buildProgram( | |
| Increment, | |
| Increment, | |
| Increment | |
| ) | |
| def clickMe2: AppAction = App.buildProgram( | |
| Add(3) | |
| ) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment