2012-08-10 50 views
2

可能重复:
Why clojure's vector function definition is so verbose?为什么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))))))) 

我的问题是,为什么不定义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)))) 
+2

检出:http://stackoverflow.com/questions/11570782/why-clojures-vector-function-definition-is-so-verbose?rq=1 – Ankur 2012-08-10 06:02:46

回答

5

的主要原因是性能

它可以帮助Clojure的编译器创建更优化的代码,如果你明确地提供了一些额外的版本,小arities(尤其是在最常用的小元数例)

这是尤其如此,如果超载版本避免需要处理可变长度参数列表(更多&),因为处理可变长度参数列表会导致比正常位置参数更多的开销。