Clojure butlast vs drop-last

nha*_*nha 8 clojure clojurescript

butlastdrop-lastClojure有什么区别?

这只是懒惰吗?我应该更喜欢一个吗?

lee*_*ski 10

另外,如果你需要实现整个系列,butlast速度要快得多,如果你看一下它们的来源是合乎逻辑的:

(def 
 butlast (fn ^:static butlast [s]
           (loop [ret [] s s]
             (if (next s)
               (recur (conj ret (first s)) (next s))
               (seq ret)))))

(defn drop-last
  ([s] (drop-last 1 s))
  ([n s] (map (fn [x _] x) s (drop n s))))
Run Code Online (Sandbox Code Playgroud)

所以drop-last使用map,同时butlast使用简单的迭代recur.这是一个小例子:

user> (time (let [_ (butlast (range 10000000))]))
"Elapsed time: 2052.853726 msecs"
nil

user> (time (let [_ (doall (drop-last (range 10000000)))]))
"Elapsed time: 14072.259077 msecs"
nil
Run Code Online (Sandbox Code Playgroud)

所以我不会盲目地偏爱一个而不是另一个.我drop-last只在我真的需要懒惰时使用,否则butlast.