When-let only executes the code after the binding if the value assigned in the let form is logically true, that is only if the value is not nil or false. In our example, this means that if get-something returns false then do-stuff will not be executed. Sometimes this is not enough and we want to execute the code even for false values. For instance if we are getting our data from a database and false values are acceptable but nil values are not, or if our functions return nil on error.

We could define a when-nlet macro which does what when-let does but executes the body whenever the binded value is not nil. By spying the code from clojure.core we obtain:

So basically what we have done is creating a macro that does multiple binds, stops after the first bind returning a nil value and executes its body if no nil value has been encountered. It is nice and it shows us how much powerful Clojure is but... if we read this tutorial on how to use monads in Clojure we quickly see that there is a simpler way to do the same thing with the maybe monad!

Each one of these function must return a Maybe type, constructed with "Nothing", or "Just 42" for instance. To simplify things, let's just say that the arrow is an extraction of the internal Maybe value. val1 will be an Int, or a String, for example. Not a Maybe Int or Maybe String.

>>= looks like a funnel, and behaves sort of like the unix pipe: take the result of the function getSomething "a" "b", and if you can extract it from a Maybe type, pipe it into the lambda function that takes 1 parameter (val1). If the return is Nothing, then we can't extract anything and stop the evaluation there.

This is why monads are needed to do I/O in Haskell: I/O functions return an action; executing it produces the new state of the world and has an I/O side-effect.

People start using Javascript on the server now using Node.JS with a lot of asynchronous functions; they write code like: