fooResult = foo(x);
if (fooResult == null) {
return null;
} else {
barResult = bar(fooResult);
if (barResult == null) {
return null;
} else {
bazResult = baz(barResult);
if (bazResult == null) {
return null;
} else {
quuxResult = quux(bazResult);
if (quuxResult == null) {
return null;
} else {
return quuxResult;
}
}
}
}
I think that's a pretty common pattern: call a function and check whether it succeeded. If it did succeed, then pass its result to the next function and repeat. If it failed, then propagate the failure outwards, skipping the rest of the computation.But that's pretty tedious and repetitive code to write. The signal to noise ratio is incredibly low. Not only that, but if I get lazy or forgetful and don't check for null in any one of those cases, my code could blow up at runtime. It would be nice if we could abstract out the pattern of error checking and propagation of errors so we didn't have to type so much boilerplate around the real meat of the computation, which is just the four function calls. Haskell's Maybe type serves precisely this purpose. The exact same code as above, in Haskell using the Maybe monad, would be:
return x >>= foo >>= bar >>= baz >>= quux
That's it! Error propagation will happen automatically, and if no errors occur along the way, we'll get the same result at the end.Now, you might think that there must be a lot going on behind the scenes to make that one-liner actually do what we want it to do. But there isn't really. Maybe comes for free in the standard libraries, and even if it didn't, we could trivially define it ourselves like this:
data Maybe a = Nothing | Just a
instance Monad Maybe where return = Just
Nothing >>= _ = Nothing
Just x >>= f = f x
That's the entire definition of the Maybe data type and its complete error propagation behavior. There's nothing more to it than that. And not only will it work in the specific example I gave, but in any situation where I have a chain of functions to call that might fail in some way. After writing that once (or not at all, since it's in the libraries), I can now apply that pattern anywhere I need it, in any program, to concisely express what took around 20 lines of onerous and error-prone repetition without the benefit of the monad.That's how monads eliminate boilerplate, and one of the reasons why you might benefit from understanding them even if you're not a Haskell user.