3 ms·
A monad is an environment in which we can sequence actions, and where the "sequencing functions" (>> and >>=) decide whether to continue or stop. The Maybe mon
by runeks 10y ago
A monad is an environment in which we can sequence actions, and where the "sequencing functions" (>> and >>=) decide whether to continue or stop.
The Maybe monad stops when it encounters a Nothing result, and continues when it encounters a Just. So:
Just 1 >> Nothing >> Just 5
will return Nothing, whereas
Just 1 >> Just 2 >> Just 5
will return Just 5.
>>= is used to take the value inside the monad (Just) for the left-hand argument, and stuff it into the right-hand argument, like so:
Just "hello" >>= Just . (++ " world")
returns Just "hello world".
- lacampbell 10y agoThose two operations make sense to me. Type signatures and all. Is that all that is needed for something to be a monad?
- moomin 10y agoThe operations also need to obey the "Monad Laws" https://wiki.haskell.org/Monad_laws https://wiki.haskell.org/Monad_laws. But the intuitive version is that anything with those two operations that doesn't smell funny is a Monad. (Think of it like implementing an interface: anything that matches the type signature will work, but if you write something silly, it won't work right)
- dllthomas 10y agoThe two things you need are actually bind (>>=) and return. As mentioned, though, you should also be sure it obeys the relevant laws.