Saturday 12 March 2016

Struggling with the State Monad

After spending hours trying to find articles explaining the damn thing without resorting to "let's take this contrived example..." or "let's take a real life example, generating pseudo-random numbers" (seriously?!), I'm still left with frustration. Eventually I'd reached out to Kaloz, who pointed me to one of his earlier explorations of the topic. His example is here, but I'm still in the dark why is it any better than a simple foldLeft. In the code below I refactored slightly Kaloz's code to keep the generic part apart from the specific solutions. A second foldLeft-using function is provided to match the signature of the function using the State monad, although I don't see any additional value in that.

Kaloz? What am I missing?

2 comments :

  1. Kaloz has pointed out that the foldLeft evaluates the result immediately, whereas the simulateMachine returns a composable Monad, thus deferring the evaluation to a later point and leaving open the possibilities to compose the result with other monads.
    However I'm still not convinced. With a slight modification of simulationWithFoldLeft (currying to the rescue) we can achieve something similar in a much simpler way:
    def simulationWithFoldLeft3(inputs: List[Input])(machine: Machine): Machine = inputs.foldLeft(machine) { (m, input) ⇒
    applyInput(input)(m)
    }
    //prepare the function
    val run: Machine ⇒ Machine = simulationWithFoldLeft3(inputs)
    //then apply it
    println(run(machine))
    //Machine(true,1,14)

    ReplyDelete
  2. I liked this article. Probably you will find it useful as well.
    https://softwarecorner.wordpress.com/2013/08/29/scalaz-state-monad/

    ReplyDelete