How Monads Can Help in Python Programming

Python assembles a bunch of functions for you in the background that normally build lists. Python doesn’t allow you to overload those functions, but if you could overload them, then a nice way to do it is via monads.


How can monads help in Python? originally appeared on Quora, the place to gain and share knowledge, empowering people to learn from others and better understand the world. You can follow Quora on Twitter, Facebook, and Google Plus.

Python supports list comprehension. You can think of list comprehension syntax as being a kind of syntactic “sugar” that hides a bunch of function calls behind some pretty looking syntax.

When you use list comprehension syntax, Python assembles a bunch of functions for you in the background. These normally build lists. But Python doesn’t directly allow you to overload those functions to give list comprehension a new meaning beyond just building lists. But curiously, if you could overload them, then a nice way to do it is via monads. In particular, Philip Wadler, in Comprehending Monads, showed that one way to overload the meaning of list comprehension corresponds precisely to using monads. The “laws” you’d expect any reasonable overloading of the syntax to obey are precisely the monad laws.

Although Python doesn’t allow you to directly overload comprehensions this way, Python makes it easy to get your hands on the abstract syntax tree of Python code so you can do your own syntactic “desugaring”. I wrote about how to do that here: Overloading Python list comprehension and here: dpiponi/Monad-Python.

The result is that you get a Python interpreter that has a built-in notation for monads, just like Haskell. (The nice thing being that it’s actually just plain old Python syntax given a new interpretation).

My favorite example is the one I wrote here: dpiponi/Monad-Python. It allows you to write code to perform a stochastic simulation involving random numbers. It looks fairly similar to code that does the sort of thing you’ve probably seen many times before: it looks like it calls a sequence of random number generators and then branches and computes something based on the outcomes. But here’s the thing that’s different: it doesn’t simply generate one outcome. It computes the probability density function. The overloaded list comprehension syntax makes it easier to collect up every single possible outcome the usual random program could have and compute the probability that each one happens. This is something tricky to implement with more conventional programming techniques.

This question originally appeared on Quora. More questions on Quora:

* Programming Languages: What is the new language to replace PHP?


* Monads: What is a monad?


* Python: Is Python becoming outdated?


Photo Credit: traffic analyzer/Getty Images