Hello,
In the Clojure language, everything except false
and nil
is true, why (true? 1)
is false
?
Thank you.
Hello,
In the Clojure language, everything except false
and nil
is true, why (true? 1)
is false
?
Thank you.
everything except
false
andnil
is true
It’s not “true”, it’s “truthy”. Only the true
value is true, and true?
checks exactly for that.
Same reason why (false? nil)
returns false
.
Hello,
Thank you so much for your reply.
What is the difference between true
and truthy
?
Truthy is anything that isn’t nil
or false
. True is the true
value.
Hello,
Thank you so much for your reply.
When should each be used? Why does Clojure have two types of true?
From Clojure - Learn Clojure - Flow Control
In Clojure, all values are logically true or false. The only “false” values are
false
andnil
- all other values are logically true.
Most of the time you can and should work with truthy/logical true values, and not worry about true
specifically. It’s quite handy.
Since actual true
is necessary to interoperate with Java, it has to exist. It’s also clear and nice to have values which are completely themselves, not some sort of stand-in like 0 or 1.
A short explorable explanation on maria.cloud. Put the cursor on the outermost expression and press Command-Enter to evaluate it and see the result on the right.
This is also a heritage from Common Lisp (and other languages), maybe Generalized Boolean is a relevant term?
one way to think about it for me is that sometimes you don’t care about boolean logic, but is looking to check if a value exists.
For example, you ran a function to read the contents of a file. But you want to check if that function is successful, but without the cumbersome method of exceptions like in java. Wouldn’t it be nice if failure to read a file is treated the same as reading an empty file?
Under this train of thought, you can treat the value nil
as empty file or an error in reading, with the other possible values as truthy. Your code is now simpler - there’s only two branches.
There’s numerous examples of this type of idiom in clojure i think.
This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.