Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is complement and not effectively the same in Clojure?

Tags:

clojure

Suppose I run the following map operation using not:

core=> (map (comp not) [true false true false])
(false true false true)

Suppose I run the following map operation using complement:

core=> (map (complement identity) [true false true false])
(false true false true)

My question is: Is complement and not effectively the same in Clojure?

(Except that compliment acts a little bit like compose in creating a partial)

like image 248
hawkeye Avatar asked Mar 17 '15 10:03

hawkeye


2 Answers

They are same in terms that you can achieve same results with little changes (like you did in your code sample). This becomes very clear if we look at complement source:

(source complement)
=>
(defn complement
  "Takes a fn f and returns a fn that takes the same arguments as f,
  has the same effects, if any, and returns the opposite truth value."
  {:added "1.0"
   :static true}
  [f]
  (fn
    ([] (not (f)))
    ([x] (not (f x)))
    ([x y] (not (f x y)))
    ([x y & zs] (not (apply f x y zs)))))

They are however very different in their meanings - not is operating on values, and it returns values (true or false). complement operates on and returns functions.

This might seem like an implementation detail, but it is very important in expressing your intensions - using complement makes it very clear that you are creating a new function, whereas not is used mostly in conditional checks.

like image 86
lobanovadik Avatar answered Oct 12 '22 17:10

lobanovadik


Similar but not the same. complement returns a function while not is evaluated immediately.

like image 38
m0skit0 Avatar answered Oct 12 '22 17:10

m0skit0