Last active
August 29, 2015 14:02
-
-
Save dsugden/95d0565e446db885433f to your computer and use it in GitHub Desktop.
This file contains 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
// we notice S => (S,A) is useful, almost composable and testable, but awkward... lets do better | |
// Lets create a type that wraps the computation, and add some useful combinators: mapResult, doAgainWithResultAndNewState | |
case class StateChange[S,A](run: S => (S,A)){ | |
def mapResult[B](f:A => B):StateChange[S,B] = StateChange{ (s:S) => | |
val(s2,a) = run(s) | |
(s2,f(a)) | |
} | |
/* | |
A magical moment!!!!!! Now I can stick 2 StateChange's together: the resulting | |
StateChange runs the first one, then uses the resulting state a the param for | |
the second one: I have now threaded my state through 2 computations. | |
*/ | |
def doWithNewState[B](f: A => StateChange[S,B]):StateChange[S,B] = StateChange{ (s:S) => | |
val(s2,a) = run(s) | |
val stateChangeToB = f(a) | |
val (s3,b) = stateChangeToB.run(s2) | |
(s3,b) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment