GZ92
GZ92

Reputation: 161

what is the equivalent of boolean? in Clojure

Scheme supports boolean? to test whether a symbol or value is of boolean type.

(boolean? #\t)
(boolean? #\f)

While in Clojure, I can only found integer?, number?, list?, etc but without boolean?.

What is the equivalent of boolean? in Clojure?

Upvotes: 4

Views: 3487

Answers (6)

tosh
tosh

Reputation: 5392

Since Clojure 1.9 there is a boolean? predicate function in clojure.core.

Upvotes: 4

David Meister
David Meister

Reputation: 4082

(defn bool? [x] (= x (boolean x)))

Upvotes: 1

Tassilo Horn
Tassilo Horn

Reputation: 821

Yet another version:

(defn boolean? [x]
  (or (true? x) (false? x)))

Upvotes: 8

Thumbnail
Thumbnail

Reputation: 13473

  • In Clojure, all values are logical: valid first arguments to an if form and all its progeny. In that sense, everything is boolean.
  • The only false values are nil and false itself. Though
    Boolean/FALSE, a static object containing false, and (Boolean. false) - a new Boolean object containing false - evaluate false. This last does not accord with how I read the documentation, but that's what Light Table is showing me. I'd say steer clear of constructing your own Booleans. Why Java allows it, I can't fathom.
  • I've never come across a case where the logic required knowing whether something was in the set #{true false}. If you need to do so, follow Shlomi's advice.
  • Many standard functions produce nil for nothing or failure. For example, a set applied to a non-member. In such cases, you may find yourself using nil? to test for nil, particularly where false would be a valid and distinct value.

Upvotes: 4

Mark Fisher
Mark Fisher

Reputation: 9886

If you're in the land of types, and want to know if something is a boolean, then as Shlomi has posted you can make a boolean? function easily enough from instance?. Here's a varargs version:

(defn bools? 
  [& xs]
  (every? (partial instance? Boolean) xs))

with outputs:

>> (bools? true) => true
>> (bools? true false) => true
>> (bools? true nil) => false

I've never needed to do this, as I've only ever dealt with values and the fact that everything in clojure is "truthy" except for false or nil.

Upvotes: 1

Shlomi
Shlomi

Reputation: 4748

you could do

(defn boolean? [x]
  (instance? Boolean x))

Upvotes: 10

Related Questions