(not) and its (complement)

Here is a quick look at the Clojure functions (not) and (complement):

user=> (not (= 1 2))
true
user=> (not (= 1 1))
false
user=> (not (> 2 3))
true
user=> (not (< 2 3))
false
;; from the cheat sheet
user=> (def not-empty? (complement empty?))
#'user/not-empty?
user=> (not-empty? []) 
false
;; now try with "not" directly
user=> (not (empty? []))
false
user=> (not-empty? [1 2])
true
user=> (not (empty? [1 2]))
true

;; from the cheat sheet
user=> (defn contains-char? [the-string, the-char]
  #_=>          (some #(= the-char %) the-string))
#'user/contains-char?
user=> (contains-char? "abc" \b)
true
user=> (contains-char? "abc" \j)
nil
;; just for fun
user=> (not (some #(= \b %1) "abc"))
false
;; from the cheat sheet
user=> (def does-not-contain-char? (complement contains-char?))
#'user/does-not-contain-char?
user=> (does-not-contain-char? "abc" \b)
false
;; with "not"
user=> (not (contains-char? "abc" \b))
false
user=> (does-not-contain-char? "abc" \j)
true
user=> (not (contains-char? "abc" \j))
true

;; so "not" and "complement" kind of do the same thing
;; from the cheat sheet
user=> (map (complement even?) '(1 2 3 4))
(true false true false)
user=> (map even? '(1 2 3 4))
(false true false true)
;; but "not" will throw an error
user=> (map (not even?) '(1 2 3 4))
ClassCastException java.base/java.lang.Boolean cannot be cast to clojure.lang.IFn  clojure.core/map/fn--4785 (core.clj:2646)
user=> (map (not #(even? %1)) '(1 2 3 4))
ClassCastException java.base/java.lang.Boolean cannot be cast to clojure.lang.IFn  clojure.core/map/fn--4785 (core.clj:2646)
user=> (map (not even? %1) '(1 2 3 4))
CompilerException java.lang.RuntimeException: Unable to resolve symbol: %1 in this context, compiling:(null:1:6) 
user=> 
;; so "not" will not work in a higher-order function
;; but everywhere else, they are kind of the same thing

 

 

You’re welcome.

There are 247 words in this article.