4

我今天有一个高阶函数的想法,但我不知道该怎么写。我有几个稀疏的惰性无限序列,我想创建一个抽象,让我检查给定的数字是否在这些惰性序列中。为了提高性能,我想将稀疏序列的值推送到 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))))

如何在不恢复到命令式风格的情况下解决这个问题?

4

2 回答 2

2

这是 Adam 解决方案的线程安全变体。

(defn make-lazy-predicate
  [coll]
  (let [state        (atom {:mem #{} :unknown coll})
        update-state (fn [{:keys [mem unknown] :as state} item]
                       (let [[just-checked remainder]
                             (split-with #(<= % item) unknown)]
                         (if (seq just-checked)
                           (-> state
                             (assoc :mem (apply conj mem just-checked))
                             (assoc :unknown remainder))
                           state)))]
    (fn [item]
      (get-in (if (< item (first (:unknown @state)))
                @state
                (swap! state update-state item))
              [:mem item]))))

也可以考虑使用 refs,但您的谓词搜索可能会被封闭事务回滚。这可能是也可能不是您想要的。

于 2010-07-19T07:26:06.640 回答
1

此功能基于核心 memoize 功能的工作原理。只有已经从惰性列表中消耗的数字才被缓存在一个集合中。它使用内置的 take-while 而不是手动进行搜索。

(defn make-lazy-predicate [coll]
  (let [mem (atom #{})
        unknown (atom coll)]
    (fn [item]
      (if (< item (first @unknown))
        (@mem item)
        (let [just-checked (take-while #(>= item %) @unknown)]
          (swap! mem #(apply conj % just-checked))
          (swap! unknown #(drop (count just-checked) %))
          (= item (last just-checked)))))))
于 2010-07-18T21:39:17.443 回答