我写了3个函数算一个元素出现在名单的次数。 我尝试了各种输入和异形,但我仍然不知道哪些功能是天下最好的堆栈使用效率和时间效率上。 请帮助我。
;; 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)))))