The reason everyone talks about monads is cause they are indeed important, and very useful. The reason you don’t understand most of the explanations you come across, quality as they are, is, they start at the far end – with definitions and concepts. We’ll try starting the other end, just for kix – with simple examples.
Forget all about “monads” for a second, and let’s talk about Option[A]. It’s a simple thing meant to save us from NullPointerExceptions, and it very well does. Like Schrödinger’s cat, it’s either Some() or None, but never null. It’s also a bit baffling at first, isn’t it?
Say you have an Option[Int] returned to you from a function that parses a String into Int. If the integer is there, you’ll do something with it; if not, then not. The first instinct of a Java/Ruby programmer? Unwrap the damned thing – it’s just a container:
val x = option.get
All good, except it will throw an exception if the option is a None. Crap. Ok, there’s that hot and functional pattern matching thing:
option match {
case Some(x) => doUsefulStuff(x)
case None => doodle()
}
Say, how much better is this compared to an if/else against null? Well, not much. So what’s all this Option stuff about, then? Here’s what:
option.map{doUsefulStuff(_)}
You know what this does – calls doUsefulStuff on the content of the Option, and return the result wrapped in another Option. If there was nothing inside the Option, it does nothing. Easy to understand, but still weird – why is it useful? Because you can safely chain it endlessly:
option.
map{findUserById(_)}.
map{reportOnUsersBuyingHabits(_)}.
map{prepareUsersAdvertisingProfile(_)}
You can run your entire computation through this pipeline w/out ever having to worry about a step failing. If it does, you’ll simply get a None at the end. Congratulations, you’re now familiar with the Simplest Useful Monad – the Option type (aka the Maybe type).
Careful with it – it will warp your brain. To quote a more-able man than myself, Mr Daniel Spiewak: “Once you start thinking about structuring your code to use Option in languages which have built-in support for it, you’ll find yourself dreaming about such patterns in other, less fortunate languages. It’s really sort of bizarre how much this little device can open your mind to new possibilities” (from his explanation of the Option.)
Questions about it that are already arising to bother you, such as “how do I know what exactly failed on a given step?” and “what if a step itself returns an Option – wouldn’t I end up with an Option[Option[A]], and how deep does that rabbit hole go?” – they will all be answered shortly.
Stay tuned!
{ 1 comments }