I am having a hard time understanding the use case of if-some. I was thinking perhaps it was a macro converting to (if (some? Collection test) true false) but from playing with it in a repl I am just not getting it. I am new to clojure but am using it. Thankfully I have some experience with lisp/scheme. I am just not getting when or why to use an if-some.
if-some is a parallel to the
some? predicate which returns
true if its argument is not
nil. These were introduced in Clojure 1.6: https://github.com/clojure/clojure/blob/master/changes.md#23-new-some-operations
In general, in Clojure,
false are considered “falsey” and everything else is considered “truthy”. That means that in the following,
do-something will be called whenever
get-data returns anything other than
(if-let [item (get-data ,,,)] (do-something item) (item-was-falsey))
Sometimes it’s important to distinguish between a
nil result (often meaning “not found”) and a
false result (i.e., “I found a Boolean value!”). That’s what
if-some let you do:
(if-some [item (get-data ,,,)] (do-something item) (item-was-nil))
In this case, if
do-something will be called (passing
false as the
item value), whereas if
nil, it will evaluate the else-expression.
Thank you for the explanation. That makes more sense than what I was finding in other online documentation.