How to distinguish a string in boolean in Clojure

I have the following statements

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

the result is working

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

the result is working

Both time results are the same. How can I properly overlay a string on boolean in clojure.

+5
source share
4 answers

If you should treat strings as boolean, this read-stringis a smart choice. But if you know that the input will be a well-formed logical (that is, either "true" or "false"), you can simply use set #{"true"}as a function:

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

Or, if you want to treat any string, but false as true (something like Clojure looks at the truth for something), you can use (complement #{"false"}):

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

- , PHP- , .

+11

java Boolean, , . clojure boolean, clojure.

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

Using read-string

(if (read-string "false")  (println "working") (println "not working"))
+2
source

You should always think about code wrapping to make such a conversion into a clearly defined function. This allows you to be more visual in your code, and also allows you to change the implementation, if necessary, to a later date (for example, if you identify other lines that should also be considered true).

I would 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
+2
source

All Articles