【发布时间】: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 毫秒”
真的
底线问题
所以,终于(抱歉冗长),我在两个问题上寻求帮助:
- 有没有办法缓存或记忆原始 else 子句中的语句,而无需每次都进行真正/实际的递归?
- 做这种事情的最惯用的 Clojure 方式是什么? (可能使用高阶函数或其他方法)
【问题讨论】: