Saturday, February 26, 2011

Clojure: Truthy and Falsey

Truthy and Falsey are important concepts in Clojure. The best description I've seen is in The Joy of Clojure, go buy it.

Depending on your language background you may have very different ideas on what evaluates to true and what evaluates to false. In Clojure, the answer to this is very straightforward.
Both nil and false are treated as "false" and everything else is treated as true.
Let's hit the REPL.
user=> (if true "yes" "no")
"yes"
user=> (if false "yes" "no")
"no"
Okay, that much should be obvious. However, it's important to note that nil is also considered false, which is why we say:
In Clojure nil and false are considered "false" and therefore we say they are both "falsey".
Another quick trip to the REPL to verify that nil is falsey.
user=> (if nil "yes" "no")  
"no"
As expected, the else is evaluated.

There are other values that are considered false in other languages, this does not apply to clojure.
All non-falsey values are considered "truthy" and evaluate as such.
Here are some common examples of truthy values in Clojure that are falsey in other languages.
user=> (if -1 "still true" "false")
"still true"
user=> (if 0 "still true" "false")
"still true"
user=> (if [] "still true" "false")
"still true"
user=> (if (list) "still true" "false")
"still true"
As it says in The Joy of Clojure: Every[thing] is "true" all the time, unless it is nil or false.

5 comments:

  1. Don't forget about the insidious "Evil False" ;-)

    (def evil-false (Boolean. "false"))

    ReplyDelete
  2. Anonymous1:48 PM

    @fogus, indeed. yet another reason people need to buy TJoC. =)

    ReplyDelete
  3. Confusing:

    user> (true? nil)
    false
    user> (false? nil)
    false
    user> (nil? false)
    false

    So nil is not false, but both are considered falsey in the if/when tests?

    ReplyDelete
  4. Anonymous2:12 PM

    @mlsci, correct, thus the term "falsey". The false? and nil? functions are always available if you want to distinguish which of the falsey values you actually have.

    (this is also discussed in The Joy of Clojure)

    Cheers, Jay

    ReplyDelete
  5. @misci I don't really know the internals of clojure, but this totally looks to me like there is internal forced evaluation to false when nil comes to the playground... Do somebody have a definitive answer?

    ReplyDelete

Note: Only a member of this blog may post a comment.