Search code examples
clojureconditional-statements

Why is Zero not falsy in Clojure?


So, in weakly-typed C, 0 is evaluated as false in a boolean context (like a conditional expression) and everything else is truthy. Modern dynamic languages seem to split on whether or not zero is falsy: Python, PHP, and Javascript say yes while Ruby, Lua, Clojure, and Racket say no.

Question is, why? I googled for my question title and found this thread on hacker news which had interesting stuff but not the answer to my question. Substituting 'lisp' for Clojure in my search yielded no historical reference.

So to be more precise in formulating my question: is there an actual technical advantage to zero evaluating as true in a conditional expression, or did it just become a quasi-standard in dynamic languages (that weren't as influenced by C) courtesy of the early lisps? Its definitely a bit odd to a programmer used to C/Python/Javascript.


Solution

  • The main reason is because many Clojure functions want to be able to easily tell "nothing" apart from "something". nil is the absence of a value, but the number 0 has a real value. An empty list is also a real thing, it's a sequence that could (for example) be conjed. (Though since Clojure allows you to (conj nil 1) that's perhaps not the best example.)

    But the key distinction is that 0 is not "nothing", it's "something". Only "nothing" (and Boolean false) are going to be falsey in Clojure. It's a different way of thinking about falseness, and it can be jarring when you're coming from a Python background (as I did too), but I've actually found it more useful than Python's falsey mechanics.