Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why is :else not (else) in clojure?

Tags:

clojure

In Clojure you can write:

(cond (= 1 2) 1 
      :else 5)

In Scheme the equivalent would be:

(cond ((= 1 2) 1)
       (else 5))

The :else 5 syntax is not as consistent as the (else 5). What is the reason the else syntax is implemented in this seemingly inconsistent way in Clojure?

like image 258
steenhulthin Avatar asked Sep 11 '25 09:09

steenhulthin


2 Answers

:else is a actually a bit of a clever trick here:

  • cond expects condition/value pairs - and :else is just a value that is "truthy" in Clojure so it guarantees that the condition is satisfied. (anything except null or false counts as "truth"). You could equally use ":donkey" as a guaranteed true condition value if you liked.
  • However, :else also conveys meaning to a human reader (i.e. this condition is the one to be executed if none of the other conditions match

So really it's just a convention that works in cond expressions and is meaningful to human readers.

like image 157
mikera Avatar answered Sep 13 '25 00:09

mikera


I think (else 5) is less consistent. (cond ...) arguments are stated as condition - value pairs. :else value is consistent because :else is just a convention - it works because :else is just an expression that's always true. There's no special rules for :else at all.

like image 45
Joost Diepenmaat Avatar answered Sep 13 '25 01:09

Joost Diepenmaat