简体   繁体   中英

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.

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 

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.

使用read-string

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

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 (eg 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM