Skip to content

Instantly share code, notes, and snippets.

@beala
Created January 26, 2015 03:56
Show Gist options
  • Save beala/f01644eb466a546e94e2 to your computer and use it in GitHub Desktop.
Save beala/f01644eb466a546e94e2 to your computer and use it in GitHub Desktop.
Trace any stateful computation in 10 lines.
/* Lift a stateful computation State[S,A] to State[(S, Seq[(S,A)]), A]
* where the (S, Seq[(S,A)]) is a history of the computation's state at
* each step: (currentState, Seq[(stateBeforeStep, resultOfStep)])
*/
def trace[S,A](iter: State[S,A]): State[(S, Seq[(S,A)]),A] = for {
preStateAndHistory <- get[(S, Seq[(S,A)])]
preState = preStateAndHistory._1
history = preStateAndHistory._2
(postState, result) = runState(for {
result <- iter
postState <- get
} yield (postState, result), preState)
_ <- set((postState, (preState, result) +: history))
} yield result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment