「純粹的遞歸」是一個虛構的術語,請原諒。何時使用純遞歸以及何時使用循環/重複?
以下是使用兩種不同遞歸方法的兩個示例。相互使用的準則是什麼?
(defn take-while
"Returns a lazy sequence of successive items from coll while
(pred item) returns true. pred must be free of side-effects."
{:added "1.0"
:static true}
[pred coll]
(lazy-seq
(when-let [s (seq coll)]
(when (pred (first s))
(cons (first s) (take-while pred (rest s)))))))
(defn take-last
"Returns a seq of the last n items in coll. Depending on the type
of coll may be no better than linear time. For vectors, see also subvec."
{:added "1.1"
:static true}
[n coll]
(loop [s (seq coll), lead (seq (drop n coll))]
(if lead
(recur (next s) (next lead))
s)))
我真的不明白你在說什麼指導方針。在第一個例子中,你根本無法選擇** loop/recur **方法,因爲'take-while'不是用在** tail-position **中。問題是什麼? **循環/重複**總是更好,如果它可以使用比函數遞歸調用和@mikera解釋了原因。 – hsestupin