[Haskell-cafe] Really confused

Philippa Cowderoy flippa at flippac.org
Wed Sep 21 14:21:37 EDT 2005


On Wed, 21 Sep 2005, Mark Carter wrote:

> I get the idea that
> data SM a = SM (S -> (a,S))
> maps a state to a result, and a new state. OTOH, looking at
>
> instance Monad SM where
> -- defines state propagation
> SM c1 >>= fc2         =  SM (\s0 -> let (r,s1) = c1 s0
>                                         SM c2 = fc2 r in
>                                        c2 s1)
> return k              =  SM (\s -> (k,s))
>
> just confuses me no end.
>

It really broke my brain for a while too - I had to graph the thing out on 
a piece of paper before I could follow what it was doing. The return 
should be easy enough, no? In the >>= code, c is "unboxed computation", fc 
is "function yielding computation", r is "result" and s is "state" - the 
first line of the let gets the result of the first computation and the 
state after it, the second line applies fc2 to the result to get the 
second computation and then the final line applies the computation to the 
intermediate state. There's a little boxing and unboxing going on, but 
that's pretty much it.

> Any pointers, like am I taking completely the wrong approach anyway? I'm also 
> puzzled
> as to how the initial state would be set.
>

You set the initial state with a "run" function, like so:

runSM (SM f) initialState = f initialState

The result will be a tuple: (result, finalState)

-- 
flippa at flippac.org

The task of the academic is not to scale great 
intellectual mountains, but to flatten them.


More information about the Haskell-Cafe mailing list