我正在使用官方指南尝试Clojure。以下是我对该链接问题8的解决方案,其中要编写一个函数opposite
,该函数应模仿complement
函数:
(defn opposite [f] (fn [& args] (not (apply f args))))
为了对比,这里是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)))))
现在,我的实现似乎只适用于一些简单的情况,例如只有几个参数:
user=> (def unequal (opposite =))
#'user/unequal
user=> (unequal 1 2)
true
user=> (unequal 1 1)
false
我的两个问题是:
- 我的
opposite
函数和complement
等价吗,还是只是看起来像?也就是说,前三个明确参数的情况是否真正必要? - 如果它们不是必需的,那么为什么补集源代码的形式在Clojure中是惯用语?
提前感谢(及致敬友好的SO!)。