Clojure 中的补充和不有效相同吗?

Is complement and not effectively the same in Clojure?

假设我运行下面的map操作使用not:

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

假设我运行下面的map操作使用complement:

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

我的问题是:complementnot 在 Clojure 中实际上是一样的吗?

(除了 compliment 在创建 partial 时有点像 compose)

相似但不相同。 complement returns 一个函数,而 not 立即计算。

它们的相同之处在于您只需稍作改动即可获得相同的结果(就像您在代码示例中所做的那样)。如果我们查看 complement 来源:

,这将变得非常清楚
(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)))))

然而,它们的含义非常不同 - not 对值进行操作,而它 returns 值(truefalse)。 complement 作用于 returns 函数。

这可能看起来像是一个实现细节,但它在表达您的意图时非常重要 - 使用 complement 可以非常清楚地表明您正在创建一个新函数,而 not 则主要使用在条件检查中。

稍微澄清一下您的问题:(comp not)(complement identity) 几乎相同,因为 (comp not) 产生的函数执行相同的操作。