【发布时间】:2021-10-15 08:31:04
【问题描述】:
这里是 Clojure 的 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)))))
为什么将其定义为多元函数?在我看来,以下实现将达到相同的结果:
(defn alternative-complement [f]
(fn [& args] (not (apply f args))))
出于什么原因,Clojure 的 complement 将无参数、单个参数和两个参数视为“特殊情况”?
【问题讨论】:
-
也许是因为编译器更容易优化 0、1 和 2 参数的具体情况?从而避免使用序列的运行时开销。
-
正是出于这个原因。在
clojure.core中还有许多其他此类方法的示例。 -
添加了here,这是可以预料的,这是一种优化。
-
我确定这个问题之前已经在这里问过,但我找不到。 stackoverflow.com/questions/10769005/… 已关闭。
标签: clojure