为什么Clojure在参数子句中定义具有冗余的函数

xia*_*owl 2 clojure

可能重复:
为什么clojure的向量函数定义如此冗长?

为了澄清我的问题,让我们以定义list*为例.

(defn list*
  "Creates a new list containing the items prepended to the rest, the
  last of which will be treated as a sequence."
  {:added "1.0"
   :static true}
  ([args] (seq args))
  ([a args] (cons a args))
  ([a b args] (cons a (cons b args)))
  ([a b c args] (cons a (cons b (cons c args))))
  ([a b c d & more]
    (cons a (cons b (cons c (cons d (spread more)))))))
Run Code Online (Sandbox Code Playgroud)

我的问题是,为什么不这样定义list*:

(defn list*
  "Creates a new list containing the items prepended to the rest, the
  last of which will be treated as a sequence."
  {:added "1.0"
   :static true}
  ([args] (seq args))
  ([a & more] (cons a (spread more))))
Run Code Online (Sandbox Code Playgroud)

mik*_*era 5

主要原因是表现.

它可以帮助Clojure编译器创建更优化的代码,如果你明确提供一些小的arities额外的版本(特别是因为小arity情况是最常用的)

如果重载版本避免处理可变长度参数列表(及更多),则尤其如此,因为处理可变长度参数列表会导致比正常位置参数更多的开销.