10
votes

In Common Lisp you use the (null x) function to check for empty lists and nil values.

Most logically this maps to

(or (nil?  x) (= '() x))

In clojure. Can someone suggest a more idiomatic way to do it in Clojure?

2
In Lisp, NIL and () (the empty list) are one and the same thing. Your code snippet is a pleonasm.Svante
Not in Clojure: (= '() nil) => false. In other Lisps, this is true.Isaac
Svante: Your statement might not be true in Clojure but I have a new favorite word.Ken
There is no null? in CL, only null (and endp).danlei

2 Answers

16
votes

To get the same result for an empty list in Clojure as you do in Common Lisp, use the empty? function. This function is in the core library: no imports are necessary.

It is also a predicate, and suffixed with a ?, making it a little clearer what exactly you're doing in the code.

=> (empty? '())
true
=> (empty? '(1 2))
false
=> (empty? nil)
true

As j-g faustus already noted, seq can be used for a similar effect.

10
votes

seq also serves as test for end, already idiomatic

(when (seq coll)
  ...)

From clojure.org lazy

It works because (seq nil) and (seq ()) both return nil.

And since nil means false, you don't need an explicit nil test.