Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 345
Isuru Avatar asked Aug 08 '12 06:08

Isuru


4 Answers

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 
like image 63
smunk Avatar answered Oct 19 '22 01:10

smunk


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.

like image 26
amalloy Avatar answered Oct 19 '22 02:10

amalloy


Using read-string

(if (read-string "false")  (println "working") (println "not working"))
like image 22
Ankur Avatar answered Oct 19 '22 02:10

Ankur


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
like image 37
mikera Avatar answered Oct 19 '22 03:10

mikera