Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does `(count nil)` return 0?

Tags:

null

clojure

In Clojure, I find this surprising:

> (count nil)
0

I would expect a type error, as in this case:

> (count 77)
java.lang.UnsupportedOperationException: count not supported on this type: Long

since nil is not a list:

> (list? nil)
false

Does nil have a special status as an empty sequence?

like image 428
Tim Culver Avatar asked Dec 08 '22 04:12

Tim Culver


1 Answers

From the official documentation:

count:

Returns the number of items in the collection. (count nil) returns 0. Also works on strings, arrays, and Java Collections and Maps

So this is the spec ;)

I imagine that it ensures that any mutating value having a "countable" type can be handled at runtime.
Indeed, any reference, referencing an allowed type (strings, arrays, and Java Collections and Maps) might target nil at some point.

like image 120
Mik378 Avatar answered Dec 14 '22 23:12

Mik378