Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Clojure idiom prefer to return nil instead of empty list like Scheme?

Tags:

idioms

clojure

From a comment on another question, someone is saying that Clojure idiom prefers to return nil rather than an empty list like in Scheme. Why is that?

Like,

(when (seq lat) ...)

instead of

  (if (empty? lat)  
    '() ...)
like image 577
Paul Lam Avatar asked May 18 '11 13:05

Paul Lam


1 Answers

I can think of a few reasons:

  • Logical distinction. In Clojure nil means nothing / absence of value. Whereas '() "the empty list is a value - it just happens to be a value that is an empty list. It's quite often conceptually and logically useful to distinguish between the two.

  • Fit with JVM - the JVM object model supports null references. And quite a lot of Java APIs return null to mean "nothing" or "value not found". So to ensure easy JVM interoperability, it makes sense for Clojure to use nil in a similar way.

  • Laziness - the logic here is quite complicated, but my understanding is that using nil for "no list" works better with Clojure's lazy sequences. As Clojure is a lazy functional programming language by default, it makes sense for this usage to be standard. See http://clojure.org/lazy for some extra explanation.

  • "Falsiness" - It's convenient to use nil to mean "nothing" and also to mean "false" when writing conditional code that examines collections - so you can write code like (if (some-map :some-key) ....) to test if a hashmap contains a value for a given key.

  • Performance - It's more efficient to test for nil than to examine a list to see if it empty... hence adopting this idiom as standard can lead to higher performance idiomatic code

Note that there are still some functions in Clojure that do return an empty list. An example is rest:

(rest [1])
=> ()

This question on rest vs. next goes into some detail of why this is.....

like image 56
mikera Avatar answered Sep 18 '22 21:09

mikera