The Hyperpessimist

The grandest failure.

Some->>, a Monadic Map in Clojure

There is a number of threading operators in Clojure, I was talking about them recently. But there is one operator that is kinda interesting, since it accidentally has similar semantics to Haskell’s fmap/<$> on the Maybe monad and OCaml’s BatOption.map/Core_kernel.Option.map.

Ok, now as I scared everybody faint of heart away using the M-word, let me explain. Clojure of course does not have Option types, Functors or similar, instead everything is a value or nil (well, nil is also a value, so this is only an approximation). Looking at it from a slightly different perspective, everything is an Option type, since the Just/Some part is the value and the Nothing/None part is nil (I am aware this is not an entirely correct comparison).

Clojure also has a number of threading operators. Among these is also an operator that threads a value through a sequence of functions only if the value is not nil, namely some->> (and of course some->), otherwise it returns nil. This sounds like an nifty addition to the Clojure zoo of threading operators, but coincidentally is also very similar to how <$>/fmap/map behave. Especially considering that some of the code I write or work with every day often uses some->> without threading at all:

1
(some->> value-might-be-nil only-works-with-non-nil)

Which is semantically very similar to Haskell:

1
mightBeNothing <$> onlyWorksWithJust

Or in OCaml

1
2
open Core_kernel.Option.Monad_infix
might_be_none >>| only_works_with_some

So even if you use Clojure, you still benefit from cool functional programming concepts. They are maybe not that prominent but waiting to be used for great good!