Alex Rivera | Logout

How to cast string to boolean in Clojure

Asked 2012-08-08T06:26:27.013
8

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.

Edit
Report

1 Answer

3

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
answered 2012-08-08T09:21:01.693

Your Answer