-
Notifications
You must be signed in to change notification settings - Fork 3
FunListMonad
Robert Peszek edited this page Sep 17, 2013
·
2 revisions
Fpiglet comes with predefined standard 'non-deterministic calculations' monad for functional lists (FunList) defined in:
fpig.funlist.functions.FunListMonad
Below is an example of non-deterministic calculation. Consider a simple game where coin is tossed, heads results in player getting one dollar and tails results in loss of one dollar. What is the likelihood of player being 2 dollars or more ahead after 4 tosses?
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)
def after4 = b(toss) << b(toss) << b(toss) << b(toss) << f([0])
def res = (length << filter (LARGER(1)) <<after4) / (length << after4)
assert res + 0.01 > 5/16 && res - 0.01 < 5/16
In the above example static curried function b
(same as bind
) is defined in FpigBase and applies to all monads registered with Fpiglet.
f
maps List to Functional List and since FunList is a monad we could have wrote:
MonadDescription m = FunListMonad.instance
m.pure(0) //same as f([0])
Note that the direction is right to left, which is the same as function composition (which is actually what <<
is).