-
Notifications
You must be signed in to change notification settings - Fork 3
MonadicComposition
Robert Peszek edited this page Sep 22, 2013
·
1 revision
- I have blogged about some more advanced monadic programming with FunList here: http://rpeszek.blogspot.com/2013/08/groovy-monads-knight-chessboard-making.html
Using FunList as monad, consider tossing a coin (see FunListMonad for explanation).
Closure toss = { x-> e(x+1) << e(x-1) << empty()} //two element list with (x+1) and (x-1), +1 represents heads (gain), -1 represents tails (loss)
Monads allow for chaining functions with monadic values. For fixes number of 'chained operations' this can be simply done like so:
MonadDescription m = FunListMonad.instance
def outcomes = m.bind(toss) << m.bind(toss) << m.bind(toss) << m.pure(initValue)
A more advance case is when we want to chain the closure 'n' times. What if we wanted to know what is the likelihood of being 2 dollars or more ahead after n tosses:
def composeNtimes = f {n, Closure c -> reduceR (COMPOSE) << take(n) << repeat( c )}
def resAfterN = {n->
def afterN = composeNtimes(n, m.bind(toss)) << m.pure([0])
(length << filter (LARGER(1)) << afterN) / (length << afterN)
}
assert resAfterN(4) + 0.01 > 5/16 && resAfterN(4) - 0.01 < 5/16
TODO describe this example.
The other way is to use monadic folds. TODO describe monadic folds.
Even more advanced examples are shown on my blog page.
See: MonadPolymorphism, FunListMonad.