为什么if-not调用"not"而不仅仅是反转参数?

dam*_*onh 7 clojure

我正在研究clojure.core的来源.

(defmacro if-not
  ([test then] `(if-not ~test ~then nil))
  ([test then else]
  `(if (not ~test) ~then ~else)))
Run Code Online (Sandbox Code Playgroud)

至于第二种形式,为什么不呢

([test then else] `(if ~test ~else ~then)

nta*_*lbs 2

这看起来只是一种编码风格。

(if-not test then else)

(if (not test) then else)

(if test else then)
Run Code Online (Sandbox Code Playgroud)

上面的代码将以同样的方式工作。有多种方法可以编写代码来完成同一件事。

宏的作者if-not可能认为这样编写代码会更好。

(defmacro if-not
  ...
  ([test then else]
    `(if (not ~test) ~then ~else)))
Run Code Online (Sandbox Code Playgroud)

当我们阅读上面的这段代码时,我们可以按照ifthenelse、 的顺序思考,非常简单。

(defmacro if-not
  ...    
  ([test then else]
    `(if ~test ~else ~then)
Run Code Online (Sandbox Code Playgroud)

是的,这会很好用。但从可读性角度来说,then和 的顺序else互换了,可能会造成混乱。

这就是为什么(在我看来)作者if-not以这种方式实现的原因。