Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure boolean confusion when entered via a string

What am I missing here?...

While this works perfectly fine:

(def env [true true true false])
=> #'clojquery.core/env
(boolean (first (drop 3 env)))
=> false

I cannot get the same behavior if I convert a string from read-line for the forth value:

(def env (do
           (println "Enter boolean: ")
           (let [in (read-line)]
             (concat [true true true] (map symbol (re-seq #"\w+" in))))))

Enter boolean: 
false
=> #'clojquery.core/env
(vec env)
=> [true true true false]
(first (drop 3 (vec env)))
=> false
(boolean (first (drop 3 env)))
=> true
(if (first (drop 3 (vec env))) "TRUE" "FALSE")
=> "TRUE"

Isn't that odd? Thank you for your help!

like image 386
Hugolin Bergier Avatar asked Nov 18 '25 15:11

Hugolin Bergier


1 Answers

In Clojure, false and nil are falsey and everything else is truthy.

You're creating a symbol from the input string. You can create a symbol from any string. A symbol is not false or nil so all symbols are truthy.

(boolean? (symbol "false")) ;;=> false -- it isn't a Boolean
(symbol? (symbol "false")) ;;=> true -- it's a Symbol
(boolean? false) ;;=> true -- false is a Boolean
(symbol? false) ;;=> false -- false isn't a Symbol

So true and false are not symbols in Clojure -- they are values.

If you're using Clojure 1.11, you can call parse-boolean on your input string to produce true or false values. However, that will throw an exception if you enter something that cannot be parsed as a Boolean value so it depends what you are trying to do.

like image 199
Sean Corfield Avatar answered Nov 21 '25 09:11

Sean Corfield



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!