Isu*_*uru 5 string boolean clojure
我有以下声明
(if "true" (println "working") (println "not working"))
Run Code Online (Sandbox Code Playgroud)
结果是 - 工作
(if "false" (println "working") (println "not working"))
Run Code Online (Sandbox Code Playgroud)
结果是 - 工作
时间结果都相同,我怎样才能在clojure中将字符串正确地转换为boolean.
ama*_*loy 11
如果你必须将字符串视为布尔值,那么这read-string是一个合理的选择.但是如果你知道输入将是一个格式良好的布尔值(即"true"或"false"),你可以使用set #{"true"}作为函数:
(def truthy? #{"true"})
(if (truthy? x)
...)
Run Code Online (Sandbox Code Playgroud)
或者,如果你想要处理任何字符串而不是"假"作为真理(大概是Clojure如何看待任何事情的真实性),你可以使用(complement #{"false"}):
(def truthy? (complement #{"false"}))
(if (truthy? x)
...)
Run Code Online (Sandbox Code Playgroud)
如果你想做一些像PHP的弱类型转换一样卑鄙的事情,你将不得不自己编写规则.
您可以创建一个新的java Boolean对象,该对象具有接受字符串的方法.如果你然后使用clojure的布尔函数,你实际上可以让它在clojure中工作.
(boolean (Boolean/valueOf "true")) ;;true
(boolean (Boolean/valueOf "false")) ;;false
Run Code Online (Sandbox Code Playgroud)
使用read-string
(if (read-string "false") (println "working") (println "not working"))
Run Code Online (Sandbox Code Playgroud)