Hmm, I see. The problem with my understanding it is that people are describing its properties and I have to build the mental model from them.
Are Python list comprehensions monads?
Well, it's the type itself that's a monad. So the question would be, are Python lists monads thanks to list comprehensions? And the answer is: Kind of. The idea of a monad in functional programming is that it's a generic type that can have a lot of different implementations.
The two operations that must be defined for a monad are:
• Return: You pass any value and it returns a monad encapsulating that value
• Bind: You pass a function taking an argument of the type wrapped by the monad and returning another value wrapped in the monad, and it returns a value of the monad
With these two operations, you can accomplish a surprising range of tasks. Python borrowed list comprehensions from Haskell, where they are based on monads — but in Python, they're kind of orphaned from their monadic roots.
As an example, lists are monads. The operator for doing calculations with the value in a monad is >>= (pronounced "bind"). To double every item in an array, you could do:
(The syntax "\n -> [n2]" defines a function that takes one argument, n, and returns a list containing n 2.)There's clearly work going on behind the scenes to pass each value in the list to the associated function as "n", and then combine all the resulting [n * 2] lists into one big list of the same type as the original. But that's all transparent to the programmer. He only sees the interface that the monad offers.