Created
February 12, 2013 18:15
-
-
Save tpolecat/4771973 to your computer and use it in GitHub Desktop.
Example usage of scalaz7's State monad.
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
| import scalaz.State // the State[S,A] type itself | |
| import scalaz.State._ // primitives like get and put are here | |
| object StateExample extends App { | |
| // A computation that produces a String | |
| val action1: State[Int, String] = | |
| for { | |
| n <- get | |
| _ <- put(n + 1) | |
| } yield "initial state was %d".format(n) | |
| // Another action that uses the first one | |
| val action2: State[Int, String] = for { | |
| s <- action1 | |
| _ <- modify[Int](_ * 3) | |
| } yield "first result was: " + s | |
| println(action2(3)) // Get the final state and the result | |
| println(action2.eval(3)) // Or just the result | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment