我正在尝试自己创建一个take
函数,但这似乎会导致堆栈溢出,知道是什么原因造成的吗?
(defn my-take-plus [n Lst LstAcc count]
(let [LstVec (into [] Lst)]
(cond (= count n) LstAcc
:else
(do
(conj LstAcc (first LstVec))
(inc count)
(my-take-plus n (apply list(rest LstVec)) LstAcc count)
)
)
)
)
(defn my-take [n Lst]
(my-take-plus n Lst [] 0)
)
此外,还有一种"clojurish"方法可以做到这一点:
(defn my-take [n data]
(when (and (pos? n) (seq data))
(lazy-seq
(cons (first data)
(my-take (dec n) (rest data))))))
这个是懒惰的,还可以防止堆栈溢出。此外,据我所知,clojure.core/take
以类似的方式实现
我会考虑使用loop/recur
策略,以便Clojure进行尾调用优化(TCO)以防止堆栈溢出。
(defn take' [n coll]
(loop [n n
acc []
coll coll]
(cond
(empty? coll) acc
((comp not pos?) n) acc
:else (recur (dec n) (conj acc (first coll)) (rest coll)))))
在您的示例中,我会考虑使用if
,因为您只需要有条件的分支。 cond
通常更像是case
语句。