4 ms·
Understanding monads in one minute
Well, not really, but maybe this will give some intuition?
It's all about function composition.
If you have
f: a -> b
g: b -> c
Then you can easily compose these functions: a => g(f(a))
However, if you want to associate extra information along with the
function result (e.g., a None flag in Option[int] say), we would have:
f: a -> M b
g: b -> M c
To compose f and g, we can no longer use a => g(f(a)) because f(a) has
type M b but g requires a b.
Instead, we can use a >>= bind operator to compose these functions as follows:
a => ( f(a) >>= g ) where >>= has type M b->(b->M c)->M c
Returning to our Option example:
f:a -> Option[b]
g:b -> Option[c]
>>= has type Option[b] -> (b->Option[c]) -> Option[c]
We can define it like this:
>>=( option_b : Option[b], g:b=>Option[c] ):Option[c] = {
if ( option_b.none_flag set ) return Option[c] with none_flag set
return g(option_b.value)
}