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 comp
ose in creating a partial
)
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.
Similar but not the same. complement
returns a function while not
is evaluated immediately.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With