Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure: Idiomatic/clean way to avoid NPE in a monad-like way

Tags:

clojure

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.

like image 263
Tony K. Avatar asked Jun 15 '15 16:06

Tony K.


1 Answers

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"
like image 176
cfrick Avatar answered Nov 09 '22 05:11

cfrick