【问题标题】:Caching the value of a "recursive" call in Clojure using recur使用 recur 在 Clojure 中缓存“递归”调用的值
【发布时间】:2012-01-31 05:14:10
【问题描述】:

我正在 Clojure 中进行 The Little Schemer 和 The Seasoned Schemer 练习,作为学习 Scheme 和 Clojure 的练习 - 尝试将其编写为惯用的 Clojure我能。英寸。 14 (Seasoned Schemer) 他们定义了函数leftmost,它应该找到第一个“原子”(意思是一个不是列表的实体,不是 Clojure 定义的一个原子)在一个列表中。这是我在 Clojure 中实现真正的递归版本:

(defn atom? [x]
  (not (coll? x)))

(defn leftmost [l]
  (cond
   (empty? l) []
   (atom? (first l)) (first l)
   :else (let [r (leftmost (first l))]
           (if (atom? r)
             r
             (leftmost (rest l))))))

为了弄清楚它的作用,下面是它的测试:

(deftest test-leftmost
  (is (= :a (leftmost [:a :b [:c :d]])))
  (is (= :a (leftmost [[:a :b] [:c :d]])))
  (is (= :a (leftmost [[] [] [[:a]] :b [:c :d]])))
  (is (= [] (leftmost-recur [[] [['()]]])))
  (is (= [] (leftmost-recur []))))

练习的关键部分是通过在:else 子句中使用 let 语句来“缓存”leftmost (first l) 的调用。

我想在 Clojure 中使用 recur 编写这个并获得尾调用优化。到目前为止我能做的最好的是:

(defn leftmost-recur [l]
  (cond
   (empty? l) []
   (atom? (first l)) (first l)
   :else (let [r (leftmost-recur (first l))]
           (if (atom? r)
             r
             (recur (rest l))))))

在 :else 子句中,我仍然有一个真正的递归,而不是 recur,因为 recur 当然必须出现在尾调用位置。该函数通过了测试,但存在真正递归的问题,包括堆栈溢出。

有没有办法在不进行真正递归的情况下“缓存”(let [r (leftmost-recur (first l))] 调用?

尝试使用 memoize

我试图考虑使用memoize,但我不确定如何记忆自递归函数。这是我的尝试,但我认为它没有达到我的预期:

(defn leftmost-recur-memoize [l]
  (Thread/sleep 100)  ; added to check whether memoize is working    
  (let [memo-leftmost (memoize leftmost-recur-memoize)]
    (cond
     (empty? l) []
     (atom? (first l)) (first l)
     :else (let [r (memo-leftmost (first l))]
             (if (atom? r)
               r
               (memo-leftmost (rest l))
               )))))

...基于测试数字:

(println (time (= :a (leftmost-recur-memoize [:a :b [:c :d]]))))
(println (time (= :a (leftmost-recur-memoize [[] [] [[:a]] :b [:c :d]]))))
(println (time (= [] (leftmost-recur-memoize [[] [['()]]]))))
;; repeat same
(println (time (= :a (leftmost-recur-memoize [:a :b [:c :d]]))))
(println (time (= :a (leftmost-recur-memoize [[] [] [[:a]] :b [:c :d]]))))
(println (time (= [] (leftmost-recur-memoize [[] [['()]]]))))
“经过时间:100.27427 毫秒” 真的 “经过时间:701.740783 毫秒” 真的 “经过时间:801.796439 毫秒” 真的 “经过时间:100.148838 毫秒” 真的 “经过时间:701.430802 毫秒” 真的 “经过时间:801.767962 毫秒” 真的

底线问题

所以,终于(抱歉冗长),我在两个问题上寻求帮助:

  1. 有没有办法缓存或记忆原始 else 子句中的语句,而无需每次都进行真正/实际的递归?
  2. 做这种事情的最惯用的 Clojure 方式是什么? (可能使用高阶函数或其他方法)

【问题讨论】:

    标签: recursion clojure


    【解决方案1】:
    1. 没有。列表的嵌套列表是一棵树,您正在执行深度优先搜索。每次下拉时,您都需要跟踪所有以前的列表,以便在您回来时可以继续检查它们。因此,这种消耗堆栈的行为实际上并不是由于存储了返回值,而是由于遍历了树。

    2. (first (flatten coll))

    【讨论】:

    • 谢谢亚历克斯,非常有帮助。我快速浏览了用于 flatten 的 Clojure 源代码,它本身似乎是递归的(不是伪递归的),因此对于这种树行走来说,似乎需要真正的递归。
    猜你喜欢
    • 1970-01-01
    • 2012-03-01
    • 1970-01-01
    • 2023-04-03
    • 2011-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多