Skip to content

Instantly share code, notes, and snippets.

@dsugden
Last active August 29, 2015 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dsugden/95d0565e446db885433f to your computer and use it in GitHub Desktop.
Save dsugden/95d0565e446db885433f to your computer and use it in GitHub Desktop.
// 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