| Consider the pattern of using None (or null) as an error. You want to compute:
var x
x=f(x)
x=g(x)
x=h(x) however, if either f,g, or h return None, then the final value of x is None. The standard way of doing this is:
def f(x):
if x==None:
return None
... The monadic solution is the Maybe monad. Maybe has two constructors, Just(x) and Nothing. The above code would be equivilent to
var x
x=Just(x)
x=x.apply(f)
x=x.apply(g)
x=x.apply(h) The definition of Maybe is pretty simple. The Just object takes a value of a given type, and will run that value through a given function:
Class Just():
def __init__(val):
this.val = val def apply(f);
return f(x) The Nothing object is even simpler:
Class Nothing():
def apply(f):
return Nothing() Using this, we can see that in our original example, once one function returns Nothing, we skip all the other functions and end up with Nothing. When a function does return something, it needs to wrap it in Just, so we have: def f(x):
...
return Just(x) In general, to be a Monad you need to satisfy the type
class Monad():
def apply(f) Of course, using Monads like this can end up being somewhat messy, so there is much syntactic sugar around them. |