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 %))
Related
I need a predicate which returns logically true if the given value is a not-empty collection and logically false if it's anything else (number, string etc.).
And more specifically, that the predicate won't throw the IllegalArgumentException if applied to single number, or string.
I came up with the following function, but I'm wondering if there is some more idiomatic approach?
(defn not-empty-coll? [x]
(and (coll? x) (seq x)))
This will satisfy following tests:
(is (not (not-empty-coll? nil))) ;; -> false
(is (not (not-empty-coll? 1))) ;; -> false
(is (not (not-empty-coll? "foo"))) ;; -> false
(is (not (not-empty-coll? []))) ;; -> nil (false)
(is (not (not-empty-coll? '()))) ;; -> nil (false)
(is (not (not-empty-coll? {}))) ;; -> nil (false)
(is (not-empty-coll? [1])) ;; -> (1) (true)
(is (not-empty-coll? '(1))) ;; -> (1) (true)
(is (not-empty-coll? {:a 1})) ;; -> ([:a 1]) (true)
EDIT: A potential use case:
Let's say we need to process some raw external data which are not (yet) under our control. Input could be for example a collection which contains either primitive values, or nested collections. Other example could be a collection holding some inconsistent (maybe broken?) tree structure. So, we can consider mentioned predicate as first line data cleaning.
Otherwise, I agree with comments that is better to explicitly separate and process collection and non-collection data.
How about using Clojure protocols and type extensions to solve this?
(defprotocol EmptyCollPred
(not-empty-coll? [this]))
(extend-protocol EmptyCollPred
Object
(not-empty-coll? [this] false)
nil
(not-empty-coll? [this] false)
clojure.lang.Seqable
(not-empty-coll? [this] (not (empty? (seq this)))))
(is (not (not-empty-coll? nil))) ;; -> false
(is (not (not-empty-coll? 1))) ;; -> false
(is (not (not-empty-coll? "foo"))) ;; -> false
(is (not (not-empty-coll? []))) ;; -> nil (false)
(is (not (not-empty-coll? '()))) ;; -> nil (false)
(is (not (not-empty-coll? {}))) ;; -> nil (false)
(is (not-empty-coll? [1])) ;; -> (1) (true)
(is (not-empty-coll? '(1))) ;; -> (1) (true)
(is (not-empty-coll? {:a 1})) ;; -> ([:a 1]) (true)
Maybe it would be cleaner to extend just String and Number instead of Object - depends on what do you know about the incoming data. Also, it would be probably better to filter out nils beforehand instead of creating a case for it as you see above.
Another - conceptually similar - solution could use multimethods.
As suggested in the comments, I would consider calling not-empty? with a non-collection argument to be an invalid usage, which should generate an IllegalArgumentException.
There is already a function not-empty? available for use in the Tupelo library. Here are the unit tests:
(deftest t-not-empty
(is (every? not-empty? ["one" [1] '(1) {:1 1} #{1} ] ))
(is (has-none? not-empty? [ "" [ ] '( ) {} #{ } nil] ))
(is= (map not-empty? ["1" [1] '(1) {:1 1} #{1} ] )
[true true true true true] )
(is= (map not-empty? ["" [] '() {} #{} nil] )
[false false false false false false ] )
(is= (keep-if not-empty? ["1" [1] '(1) {:1 1} #{1} ] )
["1" [1] '(1) {:1 1} #{1} ] )
(is= (drop-if not-empty? ["" [] '() {} #{} nil] )
["" [] '() {} #{} nil] )
(throws? IllegalArgumentException (not-empty? 5))
(throws? IllegalArgumentException (not-empty? 3.14)))
Update
The preferred approach would be for a function to only receive collection parameters in a given argument, not a mixture scalar & collection arguments. Then, one only needs not-empty given the pre-knowledge that the value in question is not a scalar. I often use Plumatic Schema to enforce this assumption and catch any errors in the calling code:
(ns xyz
(:require [schema.core :as s] )) ; plumatic schema
(s/defn foo :- [s/Any]
"Will do bar to the supplied collection"
[coll :- [s/Any]]
(if (not-empty coll)
(mapv bar foo)
[ :some :default :value ] ))
The 2 uses of notation :- [s/Any] checks that the arg & return value are both declared to be a sequential collection (list or vector). Each element is unrestricted by the s/Any part.
If you can't enforce the above strategy for some reason, I would just modify your first approach as follows:
(defn not-empty-coll? [x]
(and (coll? x) (t/not-empty? x)))
I'm hoping you know at least a little about the param x so the question becomes: Is x a scalar or a non-empty vector. Then you could say something like:
(defn not-empty-coll? [x]
(and (sequential? x) (t/not-empty? x)))
First of All, I have a Mysql table like this:
create table t (id int(11) PRIMARY KEY unsigned NOT NULL AUTO_INCREMENT, name varchar(20), age int(10));
I define a funtion that will create a row in t:
(require '[honeysql.core :as sql])
(defn do-something []
(sql/query {:insert-into :t
:values [{:name "name1" :age 10}]})
(> 3 (rand-int 5)))
And now I want to run this function until it return true but at most N times.
This take-timescode is wrong because repeat will eval the do-something function one time and then structure the lazy sequence.
(defn take-times []
(some true? (repeat 5 (do-something))))
This take-times2 will eval the do-something 5 times no matter what the do-something return.
(defn take-times2 []
(some true? (for [i (range 5)]
(do-something))))
What should I do if i do not use recursion function and macro?
This should work:
(->> (repeatedly do-something)
(take 5)
(some true?))
Update (04.11.2014):
Since repeatedly actually allows for an optional length parameter, this is also fine:
(some true? (repeatedly 5 do-something))
Example
(defn do-something
[]
;; 20% chance of true
(let [ret (rand-nth [true false false false false])]
(prn 'hello ret)
ret))
(defn run
[]
(->> (repeatedly do-something)
(take 5)
(some true?)))
(run)
;; hello false
;; hello false
;; hello true
;; => true
(run)
;; hello false
;; hello false
;; hello false
;; hello false
;; hello false
;; => nil
The reduce function has the reduced option to stop processing a sequence based on a user defined criteria.
Using the random sequence of true and false
(defn rand-seq [] (repeatedly #(rand-nth [true false false false false])))
Use reduce to build a vector until either a true is found or a maximum number of false values has been reached.
(defn at-most-or-true [s max-false]
(reduce (fn [acc v]
(if (and (not v) (< (count acc) max-false))
(conj acc v)
(reduced acc)))
[] s))
This can be tested by calling
(at-most-or-true (rand-seq) 5)
I have 2 bindings I'm calling path and callback.
What I am trying to do is to return the first non-empty one. In javascript it would look like this:
var final = path || callback || "";
How do I do this in clojure?
I was looking at the "some" function but I can't figure out how to combine the compjure.string/blank check in it. I currently have this as a test, which doesn't work. In this case, it should return nil I think.
(some (clojure.string/blank?) ["1" "2" "3"])
In this case, it should return 2
(some (clojure.string/blank?) ["" "2" "3"])
(first (filter (complement clojure.string/blank?) ["" "a" "b"]))
Edit: As pointed out in the comments, (filter (complement p) ...) can be rewritten as (remove p ...):
(first (remove clojure.string/blank? ["" "a" "b"]))
If you are so lucky to have "empty values" represented by nil and/or false you could use:
(or nil false "2" "3")
Which would return "2".
An equivalent to your JavaScript example would be:
(let [final (or path callback "")]
(println final))
If you want the first non blank string of a sequence you can use something like this:
(first (filter #(not (clojure.string/blank? %)) ["" "2" "3"]))
This will return 2
What i don't understand is your first example using the some function, you said that it should return nil but the first non blank string is "1".
This is how you would use the some function:
(some #(when-not (empty? %) %) ["" "foo" ""])
"foo"
(some #(when-not (empty? %) %) ["bar" "foo" ""])
"bar"
As others have pointed out, filter is another option:
(first (filter #(not (empty? %)) ["" "" "foo"])
"foo"
A third option would be to use recursion:
(defn first-non-empty [& x]
(let [[y & z] x]
(if (not (empty? y))
y
(when z (recur z)))))
(first-non-empty "" "bar" "")
"bar"
(first-non-empty "" "" "foo")
"foo"
(first-non-empty "" "" "")
nil
I used empty? instead of blank? to save on typing, but the only difference should be how whitespace is handled.
It was difficult for me to tell exactly what you wanted, so this is my understanding of what you are trying to do.
In my case, I wanted to find if an item in one report was missing in a second report. A match returned nil, and a non-match returned the actual item that did not match.
The following functions wind up comparing the value of a mapped value with a key.
Using something like find-first is probably what you want to do.
(defn find-first
"This is a helper function that uses filter, a comparision value, and
stops comparing once the first match is found. The actual match
is returned, and nil is returned if comparision value is not matched."
[pred col]
(first (filter pred col)))
(defn str-cmp
"Takes two strings and compares them. Returns 0 if a match; and nil if not."
[str-1 str-2 cmp-start-pos substr-len]
(let [computed-str-len (ret-lowest-str-len str-1 str-2 substr-len)
rc-1 (subs str-1 cmp-start-pos computed-str-len)
rc-2 (subs str-2 cmp-start-pos computed-str-len)]
(if (= 0 (compare rc-1 rc-2))
0
nil)))
(defn cmp-one-val
"Return nil if first key match found,
else the original comparision row is returned.
cmp-row is a single sequence of data from a map. i
cmp-key is the key to extract the comparision value.
cmp-seq-vals contain a sequence derived from
one key in a sequence of maps.
cmp-start and substr-len are start and stop
comparision indicies for str-cmp."
[cmp-row cmp-key cmp-seq-vals cmp-start substr-len]
(if (find-first #(str-cmp (cmp-key cmp-row) %1 cmp-start substr-len) cmp-seq-vals)
nil
cmp-row))
I have this Clojure code:
(defn apply-all-to-arg [& s]
(let [arg (first s)
exprs (rest s)]
(for [condition exprs] (condition arg))))
(defn true-to-all? [& s]
(every? true? (apply-all-to-arg s)))
This is test code:
(apply-all-to-arg 2 integer? odd? even?)
=> (true false true)
(every? true? (apply-all-to-arg 2 integer? odd? even?)
=> false
(true-to-all? 2 integer? odd? even?)
=> true
My question is:
Why does the function true-to-all? return true (it must have returned false instead)
true-to-all? calls apply-all-to-arg with the single argument s. So you're not calling (every? true? (apply-all-to-arg 2 integer? odd? even?), but rather:
(every? true? (apply-all-to-arg (list 2 integer? odd? even?))
So in apply-all-to-arg the value of arg will be that list and the value of exprs will be the empty list. Since every? will be true for the empty list no matter what the condition is, you'll get back true.
To fix this you can either change apply-all-to-arg, so that it accepts a list instead of a variable number of arguments, or you can change true-to-all?, so that it passes the contents of s as multiple arguments rather than a single list (by using apply).
The default Clojure function that creates a function that applies several functions to one argument in parallel is juxt:
=> ((juxt integer? odd? even?) 2)
[true false true]
=> (every? true? ((juxt integer? odd? even?) 2))
false
=> (defn true-to-all? [a & fns]
(every? true? ((apply juxt fns) a)))
=> (true-to-all? 2 integer? odd? even?)
false
If the functions you combine with juxt all take multiple arguments it works as well
=> ((juxt + - / *) 6 3)
[9 3 2 18]
Because when you call true-to-all?, the parameter s is a list, so you are effectively calling (apply-all-to-arg '(2 integer? odd? even?))
Try defining true-to-all? like this:
(defn true-to-all? [& s]
(every? true? (apply apply-all-to-arg s))
You can also defined your function like below to make it more clear.
(defn apply-all-to-arg [v & fns]
(map #(% v) fns))
As this makes the function definition clear that it takes a value and optional functions to apply to that value.
At the home site of Clojure, there is the following statement:
Strings, numbers, characters, true,
false, nil and keywords evaluate to
themselves.
Is there a single combined predicate that tests for any of these, combining string?, number?, char?, true?, false?, nil?, and keyword?. Should I just use (complement symbol?)?
Maybe I'm missing something, but you could use the following to test for any of those conditions and return true if one is true:
(defn self-eval?
[x]
(or (string? x)
(number? x)
(char? x)
(keyword? x)
(true? x)
(false? x)
(nil? x)))
It's easy enough to write a macro that asks "does the given expression evaluate to itself". In fact this is a good example of tasks that can only be done with a macro because they need to see the argument both evaluated and unevaluated.
(defmacro selfp [a] `(= ~a (quote ~a)))
#'user/selfp
user> (selfp 1)
true
user> (selfp +)
false
user> (selfp [1 2])
true
user> (selfp '(+ 1 2 3))
false
While strings, numbers, characters, keywords, and the booleans are all self-evaluating, other things such as [1 2] are as well,so this may not be a useful test in general.
Another option is to create a function that uses a map:
(defn myclassifier? [x]
(let [types-I-care-about #{java.lang.Sring ...}]
(if (types-I-care-about (type x))
true
false)))
Another option which may have better performance is to use java's dynamism:
(extend-type Object
IMyClassifier
(myclassifier? [x]
(let [c (.getClass x)]
(if (types-I-care-about (type c))
(do
(extend-type (.getClass x)
IMyClassifier
(myclassifier? [x] true))
true)
false))))
where types-I-care-about is a set of types you care about.