gpt4 book ai didi

recursion - 何时使用纯递归,何时使用循环/递归?

转载 作者:行者123 更新时间:2023-12-04 06:21:46 24 4
gpt4 key购买 nike

“纯递归”在这里是一个虚构的术语,请见谅。

以下是使用两种不同递归方法的两个示例。两者之间的使用指南是什么?

(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 不消耗堆栈空间 - 因此,如果您要进行可能导致 StackOverflowError 的深度嵌套递归,这是正确的选择。
  • 循环/重复更快 - 它是 Clojure 中最有效的构造之一,如果正确完成,它应该与 Java 代码中等效的 for 循环的速度相匹配
  • 正常递归更惯用 - 平均而言,它倾向于为您提供更清晰、功能更强大的代码,而 loop/recur 倾向于将您推向命令式、迭代式
  • loop/recur 有更多限制 - 你只能在尾部位置递归,你不能在两个不同的函数之间进行相互递归等等。有时根本不可能使循环/递归工作,在其他时候你可能需要扭曲你的代码来这样做.
  • 关于recursion - 何时使用纯递归,何时使用循环/递归?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14272533/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com