Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure not nil check

Tags:

clojure

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??

like image 330
Steve Kuo Avatar asked Aug 07 '12 21:08

Steve Kuo


2 Answers

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) 
like image 151
liwp Avatar answered Oct 06 '22 09:10

liwp


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  
like image 27
Arthur Ulfeldt Avatar answered Oct 06 '22 09:10

Arthur Ulfeldt