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, nil
and 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 nil
or false
:
(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 true
/false
result (i.e., “I found a Boolean value!”). That’s what some?
and if-some
let you do:
(if-some [item (get-data ,,,)]
(do-something item)
(item-was-nil))
In this case, if get-data
returns false
, do-something
will be called (passing false
as the item
value), whereas if get-data
returns 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.
Ken
This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.