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

I'm a little upset that some of Clojure's built-in functions have what seems inconsistent to me.

I am trying to do this:

(let [kwns (namespace (keyword v))] ...) 

in the context where v may be nil . The keyword function works as I expected (returns nil ), but the namespace throws away the NPE.

I got the impression that monads were not often used in Clojure, because nil-punning seems like an idiomatic form (as this article goes on for about).

I was expecting newbies to go zero and not throw NPE. When this inconsistency raises its ugly head, what is the recommended way to keep the code clean .... peppering nil checks my code - this is not the answer I want, of course.

+6
source share
1 answer

Will 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" 
+10
source

Source: https://habr.com/ru/post/989143/


All Articles