I'm a little chagrinned that some of the built-in Clojure functions have what seems to me to be an inconsistent behavior.
I'm trying to do this:
(let [kwns (namespace (keyword v))]
...)
in a context where v might be nil
. The keyword
function works as I'd expect (returns nil
), but namespace throws a NPE.
I was under the impression that monads were not often used in Clojure since nil-punning seems to be the idiomatic form (as this article carries on about at length).
I expected kwns to come out nil, not throw an NPE. When this inconsistency raises its ugly head, what is the recommended way to keep the code clean....peppering nil
checks into my code is not the answer I'm wanting, of course.
Would some->
work for you?
user=> (doc some->)
-------------------------
clojure.core/some->
([expr & forms])
Macro
When expr is not nil, threads it into the first form (via ->),
and when that result is not nil, through the next etc
nil
user=> (some-> nil keyword namespace)
nil
user=> (some-> "user/a" keyword namespace)
"user"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With