Is there a quick way to test nil args in a Clojure function?

In the Phil Hagelberg gripes file, he claims the following about Clojure:

nil everywhere and causes errors that are hard to find source

Now Phil is a smart guy who has made a big contribution to the Clojure community and everyone uses his stuff, so I thought it was worth considering for a moment.

One easy way to control nil args functions is to throw an error:

(defn myfunc [myarg1] (when (nil? myarg1) (throw (Exception. "nil arg for myfunc"))) (prn "done!")) 

These two additional lines for the argument reflect the pattern. Is there an idiomatic way to remove them using metadata or macros?

My question is, is there a quick way to test Clojure function for nil args?

+7
null clojure
source share
1 answer

For these situations, there is a clojure language solution: http://clojure.org/special_forms#toc10

 (defn constrained-sqr [x] {:pre [(pos? x)] :post [(> % 16), (< % 225)]} (* xx)) 

Adapted to your requirements:

 (defn constrained-fn [ x] {:pre [(not (nil? x))]} x) (constrained-fn nil) => AssertionError Assert failed: (not (nil? x)) ...../constrained-fn (form-init5503436370123861447.clj:1) 

And there is also a @fogus contrib core.contracts library , a more sophisticated tool

Additional information on this page http://blog.fogus.me/2009/12/21/clojures-pre-and-post/

+6
source share

All Articles