Python Monads - new approach
I wondered if monads (I probably mean do-syntax) could be implemented in Python. I even googled, but the results1 were not good: in particular, the implementation I found couldn’t work with List monad.
The List monad is something I really like (it helps with Project Euler, for example), and I was also able to implement the awesome Probability monad2. So my implementation maybe of some interest. There are other notable things which I liked, for example a lambda-based syntax to use needed (and only needed) bound variables.
I must admit that I’m not sure these are exactly monads as in Haskell, but they seem to resemble the do-notation. I like do-notation, call me n00b if you want to. I even managed to use <- as an operator, and don’t ask me how.
Okay, take a look:
from monads import do, List, Maybe, Probability, mreturn, Var, guard
# this is a List monad:
l2 = do( Var('a') <- List(lambda: [1, 2, 3]),
Var('b') <- List(lambda a: [a + 1, a + 9, a * 40]),
Var('c') <- List(lambda a: xrange(a + 5)),
guard(lambda b: b < 30),
mreturn(lambda b, c: (b, c)) )
print l2.run()
# this is Maybe, and it's, of course, lazy
l5 = do( Var('a') <- Maybe(lambda: (True, 7)),
Var('b') <- Maybe(lambda: (False, False)),
Var('c') <- Maybe(lambda a: a / 0),
mreturn(lambda a, c: (c, a) ) )
print l5.run()
# and this is Probability Monad
# in this example it calculates probability
# of two coins landed on same sides
coin = Probability(lambda: [(1, 0.5), (0, 0.5)])
l8 = do( Var('fc') <- coin,
Var('sc') <- coin,
mreturn(lambda fc, sc: fc == sc) )
print l8.run()
The Probability monad is the most interesting of all.
I’m pretty sure there will be no problem in implementing other monads, which are left as an exercise to the reader ;-)
Please clone the github repo3 and try it out!
If you subscribe to my feed4, I promise to show you something a little bit more useful soon.
Please send your comments, ideas, rants and job offers at v.golev@gmail.com.
Made with Nginx, Jekyll, Git, EC2 and Emacs.
Regarding all the advertising and readability money-related stuff: I'm sorry. I'm really interested in whether one can make money by showing ads in his blog. Seems like I can't. If someone is really annoyed by adwords, drop me a line, I'll reconsider.