本文介绍了哪个函数在堆栈使用效率和时间方面是最好的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我写了3个函数来计算一个元素出现在列表中的次数。
我尝试了各种输入和分析它,但我仍然不知道哪个函数是最好的堆栈使用效率和时间效率。请帮我。
;;使用累加器
(defn count-instances1 [a-list an-element]
(letfn [(count-aux [list-aux acc]
(cond
list-aux)acc
:else(if(=(first list-aux)an-element)
(count-aux(rest list-aux)(inc acc))
-aux(rest list-aux)acc)))]
(count-aux a-list 0)))
;正常计数
(defn count-instances2 [a-list an-element]
(cond
(empty?a-list)0
:else
=(first a-list)an-element)
(+ 1(count-instances2(rest a-list)an-element))
))))
;;使用循环。这有帮助吗?
(defn count-instances3 [a-list an-element]
(loop [mylist a-list acount 0]
(if(empty?mylist)
acount
(if(=(first mylist)an-element)
(recur(rest mylist)(inc acount))
(recur(rest mylist)acount))))
解决方案循环/重复版本是正确的方法。由于JVM的限制,Clojure无法优化尾调用。
I wrote 3 functions that count the number of times an-element appears in a-list.
I tried various inputs and profiled it but I still dont know which function is the best in terms of stack usage efficiency and time efficiency. Please Help me out.
;; Using an accumulator
(defn count-instances1 [a-list an-element]
(letfn [(count-aux [list-aux acc]
(cond
(empty? list-aux) acc
:else (if (= (first list-aux) an-element)
(count-aux (rest list-aux) (inc acc))
(count-aux (rest list-aux) acc))))]
(count-aux a-list 0)))
;; Normal counting
(defn count-instances2 [a-list an-element]
(cond
(empty? a-list) 0
:else
(if (= (first a-list) an-element )
(+ 1 (count-instances2 (rest a-list) an-element))
(count-instances2 (rest a-list) an-element))))
;; using loop. does this help at all?
(defn count-instances3 [a-list an-element]
(loop [mylist a-list acount 0]
(if (empty? mylist)
acount
(if (= (first mylist) an-element)
(recur (rest mylist)(inc acount))
(recur (rest mylist) acount)))))
解决方案 The loop/recur version is the right way. Clojure cannot optimize tail calls due to limitations of the JVM.
这篇关于哪个函数在堆栈使用效率和时间方面是最好的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!