Ask HN: Are Monads Really That Hard?
I've been experiencing something lately. I don't understand the difficulty of monads. So here I present my understanding of Monads in the hope that someone will be able to point me in the right direction, or at least point out something that I'm missing.
* Monads Hide Failure (kinda)
Monads allow you to call a function that may or may not (Maybe/Just/Nothing) return the value you need in the next function. If Nothing is returned, you can pass Nothing through your future function calls or composed functions with no ill effects.
* Nesting Monads
You can nest Monads, or use do notation, to create easily replaceable failure possible sections of code.
foo :: Maybe Integer
foo = do
x <- someMonadicFunction
y <- someOtherMonadicFunction
Just (x + y)
someMonadicFunction and someOtherMonadicFunction can be anything that returns Nothing or Integer and it doesn't matter if they fail because the do will return Nothing in that case.# End
I keep reading about how Monads are a really hard topic, so I think it's possible that I'm not looking at the right pieces here.
So my question is, where do I go from here? Do I understand Monads, or am I missing something here?
8 comments
[ 2.7 ms ] story [ 23.8 ms ] threadTry to solve as many problems as you can, using monads. When you will be comfortable with aspect oriented programming (which the monads encourage), and easily speak functional language, then you can tell yourself that you have now mastered the concept. Even after that practice hard.
int x = 15; int *y = &x;
The hard part is using it to solve your problems.
You can use the same 'monad pattern' for a variety of stuff such as state computations to mimic mutability, asynchronous pipelining, IO (which if i'm not mistaken is pretty similar to the async pipelining), etc.
A 'monad' is just a term for objects that have flatmap(scala)/selectmany(.NET)/bind(Haskell?) and for comprehension/Do notation is just a convenient pattern built into the languages for working with them.
My advice: stop trying to think of particular ways monads can be used. Rather, you need to understand it as embodying a special flavor of embedding values and functions from one space (the space of simple types a, a -> m b) into another (the space of types m a, m a -> m b).
So, bind, apply and map are just ways of lifting different-shaped functions into (m a -> m b):
The moment you start trying to understand these with some first-order metaphor, you know you've lost the way! :)