Reputation: 48769
In Clojure, what is the difference between the true?
function and the boolean
function?
I see from the source code that a difference does exist (meta-information removed):
(defn boolean [x] (clojure.lang.RT/booleanCast x))
(defn true? [x] (clojure.lang.Util/identical x true))
Upvotes: 2
Views: 116
Reputation: 13473
Function boolean
is a type cast to Clojure's boolean values true
or false
. It works according to the rules of truthiness as exercised by if
and all its progeny: nil
and false
act false; everything else acts true.
You could define it as
(defn boolean [x]
(case x
(nil false) false
true))
Function true?
determines whether the argument is the Clojure value true
. You could define it as
(defn true? [x] (identical? true x))
Thus (boolean :whatever)
is true
, whereas (true? :whatever)
is false
.
There are some nasties lurking under the surface, due to Java allowing new
Boolean
objects to be created. More later.
Upvotes: 1
Reputation: 48769
As you can see from the source code, true?
returns true
if the value is identical to true
. boolean
returns true
if the value is merely truthy (all values except false
and nil
).
=> (map true? [true 0 1 :a])
(true false false false)
=> (map boolean [true 0 1 :a])
(true true true true)
Upvotes: 3