Created
January 26, 2015 03:56
-
-
Save beala/f01644eb466a546e94e2 to your computer and use it in GitHub Desktop.
Trace any stateful computation in 10 lines.
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
/* 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