Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

So, a sort of sandbox function?


Yes.

But, more like sandbox type.


Hmm, I see. Does it also execute code, like a sort of exception handler, or is it just for limiting/allowing access to scope?


A monad is a type that has certain associated functions — to wrap values in the monad and do calculations on what's inside. The type itself obviously cannot execute code, but the associated functions obviously do. Monads can be used to implement exceptions.

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:

    [1, 2, 3] >>= \n -> [n * 2]
(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.


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.


This makes it much clearer, thanks. Those two operations weren't mentioned anywhere else that I saw, and they are very helpful in explaining what monads are.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: