我今天有一个高阶函数的想法,但我不知道该怎么写。我有几个稀疏的惰性无限序列,我想创建一个抽象,让我检查给定的数字是否在这些惰性序列中。为了提高性能,我想将稀疏序列的值推送到 hashmap(或集合)中,并在必要时动态增加 hashmap 中值的数量。由于惰性序列的稀疏性,自动记忆不是这里的答案。
可能代码最容易理解,所以这就是我到目前为止所拥有的。如何更改以下代码以使谓词使用封闭的哈希图,但如果需要增加哈希图的大小并重新定义自身以使用新的哈希图?
(defn make-lazy-predicate [coll]
"Returns a predicate that returns true or false if a number is in
coll. Coll must be an ordered, increasing lazy seq of numbers."
(let [in-lazy-list? (fn [n coll top cache]
(if (> top n)
(not (nil? (cache n)))
(recur n (next coll) (first coll)
(conj cache (first coll)))]
(fn [n] (in-lazy-list? n coll (first coll) (sorted-set)))))
(def my-lazy-list (iterate #(+ % 100) 1))
(let [in-my-list? (make-lazy-predicate my-lazy-list)]
(doall (filter in-my-list? (range 10000))))
如何在不恢复到命令式风格的情况下解决这个问题?