2012-08-10 54 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(尤其是在最常用的小元數例)

這是尤其如此,如果超載版本避免需要處理可變長度參數列表(更多&),因爲處理可變長度參數列表會導致比正常位置參數更多的開銷。