Isuru
Isuru

Reputation: 8183

How to cast string to boolean in Clojure

I have following statements

(if "true"  (println "working") (println "not working"))

result is - working

(if "false"  (println "working") (println "not working"))

result is - working

Both the time result is same, How can I properly cast string to boolean in clojure.

Upvotes: 8

Views: 9561

Answers (4)

amalloy
amalloy

Reputation: 91982

If you must treat strings as booleans, read-string is a reasonable choice. But if you know the input will be a well-formed boolean (ie, either "true" or "false"), you can just use the set #{"true"} as a function:

(def truthy? #{"true"})
(if (truthy? x)
  ...)

Or, if you want to treat any string but "false" as truthy (roughly how Clojure views truthiness on anything), you can use (complement #{"false"}):

(def truthy? (complement #{"false"}))
(if (truthy? x)
  ...)

If you want to do something as vile as PHP's weak-typing conversions, you'll have to write the rules yourself.

Upvotes: 12

mikera
mikera

Reputation: 106361

You should always think about wrapping code to do this kind of conversion into a clearly-named function. This enables you to be more descriptive in your code, and also allows you to change the implementation if needed at a later date (e.g. if you identify other strings that should also be counted as truthy).

I'd suggest something like:

(defn true-string? [s]
  (= s "true"))

Applying this to your test cases:

(if (true-string? "true")   (println "working") (println "not working"))
=> working

(if (true-string? "false")  (println "working") (println "not working"))
=> not working

Upvotes: 3

smunk
smunk

Reputation: 324

You can create a new java Boolean object, which has a method that accepts a string. If you then use clojure's boolean function you can actually have it work in clojure.

(boolean (Boolean/valueOf "true")) ;;true
(boolean (Boolean/valueOf "false")) ;;false 

Upvotes: 15

Ankur
Ankur

Reputation: 33637

Using read-string

(if (read-string "false")  (println "working") (println "not working"))

Upvotes: 5

Related Questions