In Haskell, we have the syntax sugar ' do ' to help express the monad operation. We also have the corresponding syntax sugar ' for ' in Scala.
The for expression will be transformed by Scala compiler, with the following simple examples:
for { <- foo <-yield (A + B)
===>
Foo.flatmap ((a) + = {= = {+ b })})
So we need to implement two methods Flatmap and map.
or using the previous state Monad as an example, we add flatmap and map to the type State.
Case class State[s, a] (runstate:s = (S, A)) (implicit m:monad[({type m[a] = state[s, A]}) #M]) { = = B) : State[s, b] = M.bind (This, (A:A) and M.ret (f (a))) = State[s, b]): State[s, b] = M.bind (
this
, f)}
Here we use an implicit parameter, and then we can use RET and bind directly.
Add a helper to simplify monad[({type m[a] = State[s, A]}) #M].ret
Def Ret[s, A] (A:A): State[s, A] = monad[({type m[a] = State[s, A]}) #M].ret (a)
Well, we can use the for expression, as in the following example:
Object Main { import statemonad._ def main (args:array[string]) { for { <-ret [int, int] (3) <-Ret[int, Int] (4) yield (A +b) println (r.runstate ( 1) }}
Using the for expression in Scala for Monad operations