I am working through some Clojure tutorials and one of the problems is: Implement (boolean x), which works like the built-in boolean function: for nil and false, it returns false, and for all other values it returns true. You can use if in its implementation, but not the build-in boolean.
I cannot figure out how to do this with just the if statement. This works, but is there a better way?
(defn boolean [x]
(cond
(= x nil) false
(= x false) false
:else true))
nil and false are both 'falsey' (i.e. are equivalent to false in a boolean context) so you can do:
(defn boolean [x]
(if x true false))
if expressions are of the form (if condition true-expr false-expr) so if condition evaluates to true the entire expression evaluates to true-expr otherwise false-expr. So if x is truthy (i.e. not nil or false) the expression will evaluate to true. If x is falsey (nil and false are the only falsey values in clojure) then false is returned.
maybe like this?
(defn my-boolean [val]
(not (or (nil? val) (false? val))))
Related
I have a substitute function that will take in an expression such as (or false x y) and a binding map such as '{x false, y true} and will return the list with the appropriate substitutions. The result is in l and displayed. How might I pass l into another function to do some other processing? The definition for the function I'm passing to looks like this:
(defn f [expression]
)
I have tried passing l as a parameter when calling f, but I get the following error:
IllegalArgumentException Don't know how to create ISeq from: clojure.lang.Symbol clojure.lang.RT.seqFrom (RT.java:550)
Here is my substitute function:
(defn deep-substitute [m l]
(map (fn [i]
(if (seq? i)
(deep-substitute m i)
(m i i)))
l
(f 'l)))
My new function fully works the way I expect it to when calling it with an unevaluated list, but not when I pass it an unevaluated list.
The job of deep-substitute is to fill in a template form and return it. The problem gets harder if you try to make deep-substitute also responsible for doing the next step in the transformations as well. Perhaps let it return the value, then pass that value on to another transform function after it's returned.
Here's an annotated working example:
user> (defn deep-substitute [m l]
(map (fn [i]
(if (seq? i) ;; if this is a sequence,
(deep-substitute m i) ;; finish the sequence and include the result here
(get m i i))) ;; otherwise get the new value from the map, if found
l)) ;; if it's not found, us the value unchanged.
#'user/deep-substitute
then test it on your example:
user> (deep-substitute '{x false, y true} '(or false x y))
(or false false true)
and a more nested example:
user> (deep-substitute '{x false, y true} '(or false (and x (or y x)) y))
(or false (and false (or true false)) true)
a common next step is to wrap that in a macro so it can modify forms before they are evaluated, then evaluate that newly created from to find out what value it becomes:
user> (defmacro dsub [m l]
(deep-substitute m l))
#'user/dsub
and test it
user> (dsub {x false, y true} (or false (and x (or y x)) y))
true
user> (dsub {x false, y true} (or false x))
false
or pass the resulting form (unevaluated) into another function by nesting it:
user> (defn f [expression]
(reverse expression))
#'user/f
user> (f (deep-substitute '{x false, y true} '(or false (and x (or y x)) y)))
(true (and false (or true false)) false or)
A common pattern is to use the threading macros -> ->> etc. to pass the result from transform to transform until the final result is made by composing many simple operations:
user> (->> '(or false (and x (or y x)) y)
(deep-substitute '{x false, y true})
f
(deep-substitute '{false, 41 true 42}))
(42 (and 41 (or 42 41)) 41 or)
first try with the basic approach of the passing list as an argument to the function. You can refer below example
(defn passlist [a]
(println a))
(passlist '(1 2 3))
Output will:
#'user/passlist
(1 2 3)
In Clojure, what is the difference between the true? function and the boolean function?
I see from the source code that a difference does exist (meta-information removed):
(defn boolean [x] (clojure.lang.RT/booleanCast x))
(defn true? [x] (clojure.lang.Util/identical x true))
As you can see from the source code, true? returns true if the value is identical to true. boolean returns true if the value is merely truthy (all values except false and nil).
=> (map true? [true 0 1 :a])
(true false false false)
=> (map boolean [true 0 1 :a])
(true true true true)
Function boolean is a type cast to Clojure's boolean values true or false. It works according to the rules of truthiness as exercised by if and all its progeny: nil and false act false; everything else acts true.
You could define it as
(defn boolean [x]
(case x
(nil false) false
true))
Function true? determines whether the argument is the Clojure value true. You could define it as
(defn true? [x] (identical? true x))
Thus (boolean :whatever) is true, whereas (true? :whatever) is false.
There are some nasties lurking under the surface, due to Java allowing new
Boolean objects to be created. More later.
Is Clojure's logical and different from the normal logical and (&&)? Why does this yield true
((and odd? #(> 10 %)) 6)
Doesn't and need 2 true statements to return true?
and doesn't necessarily return true. It actually returns false or nil if any of the given elements is false or nil. If none of them are, then it returns the very last element (it does not return true).
In your case the and returns the function #(> 10 %) (and nothing else) which is then applied to 6 which yields true. This is because both functions are neither nil nor false.
This is how the steps would work:
((and odd? #(> 10 %)) 6)
(#(> 10 %) 6)
;; => true
What you're looking for is to compose predicate functions:
((every-pred odd? #(> 10 %)) 6) ;; => false
FYI: There is also it's complement "or": some-fn.
In Clojure nil? checks for nil. How does one check for not nil?
I want to do the Clojure equivalent of the following Java code:
if (value1==null && value2!=null) {
}
Follow-up: I was hoping for a not nil check instead of wrapping it with not. if has a if-not counterpart. Is there such a counterpart for nil??
After Clojure 1.6 you can use some?:
(some? :foo) => true
(some? nil) => false
This is useful, eg, as a predicate:
(filter some? [1 nil 2]) => (1 2)
Another way to define not-nil? would be using the complement function, which just inverts the truthyness of a boolean function:
(def not-nil? (complement nil?))
If you have several values to check then use not-any?:
user> (not-any? nil? [true 1 '()])
true
user> (not-any? nil? [true 1 nil])
false
If you are not interested in distinguishing false from nil, you can just use the value as the condition:
(if value1
"value1 is neither nil nor false"
"value1 is nil or false")
In Clojure, nil counts as false for the purposes of conditional expressions.
As a result (not x) works actually works exactly the same as as (nil? x) in most cases (with the exception of boolean false). e.g.
(not "foostring")
=> false
(not nil)
=> true
(not false) ;; false is the only non-nil value that will return true
=> true
So to answer your original question you can just do:
(if (and value1 (not value2))
...
...)
condition: (and (nil? value1) (not (nil? value2)))
if-condition: (if (and (nil? value1) (not (nil? value2))) 'something)
EDIT:
Charles Duffy provides correct custom definition for not-nil?:
You want a not-nil? Easily done: (def not-nil? (comp not nil?))
If you want your test to return true when given false, then you need one of the other answers here. But if you just want to test that returns a truthy value whenever it's passed something other than nil or false, you can use identity. For example, to strip nils (or falses) from a sequence:
(filter identity [1 2 nil 3 nil 4 false 5 6])
=> (1 2 3 4 5 6)
You can try when-not :
user> (when-not nil (println "hello world"))
=>hello world
=>nil
user> (when-not false (println "hello world"))
=>hello world
=>nil
user> (when-not true (println "hello world"))
=>nil
user> (def value1 nil)
user> (def value2 "somevalue")
user> (when-not value1 (if value2 (println "hello world")))
=>hello world
=>nil
user> (when-not value2 (if value1 (println "hello world")))
=>nil
If you want a not-nil? function, then I'd suggest just defining it as follows:
(defn not-nil?
(^boolean [x]
(not (nil? x)))
Having said that it is worth comparing the usage of this to the obvious alternative:
(not (nil? x))
(not-nil? x)
I'm not sure that introducing an extra non-standard function is worth it for saving two characters / one level of nesting. It would make sense though if you wanted to use it in higher order functions etc.
One more option:
(def not-nil? #(not= nil %))
What is fundamental difference for having a '?' in every? and not in some functions of clojure?
user> (every? true? [true true false])
false
user> (some true? [true false false])
true
Thanks.
every? returns true or false, so it gets a question mark. some doesn't return a boolean, it returns "the first logically true value returned by pred", and returns nil otherwise.
Here's the lame example I came up with:
user=> (some #(if (= 0 %) 1 0) [1 3 5 0 9])
0
The first element in the collection gets passed into the predicate, the predicate evaluates to 0, which is logically true so some returns 0. you can see some is not returning true or false.
So every? gets a question mark because it returns true or false.
some returns the value returned by pred or nil, so it doesn't get a question mark.
some doesn't necessarily return a Boolean, whereas every? always does. See the documentation.
Returns the first logical true value of (pred x) for any x in coll,
else nil. One common idiom is to use a set as pred, for example
this will return :fred if :fred is in the sequence, otherwise nil:
(some #{:fred} coll)