2

我有一个无限的惰性序列,它产生一个“前导”和一个“模式重复”,这种序列的一个简单示例可以在 Clojure 中实现:

(def infinite-lazy-sequence
  (lazy-cat [4] (cycle [1 2 3])))

=> (take 20 infinite-lazy-sequence)
(4 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1)

我想得到一个set形成这个的元素infinite-lazy-sequence,这是一种使用它来实现它的方法loop

(loop
  [[head & tail] infinite-lazy-sequence
   result #{}]
  (if (contains? result head)
    result
    (recur tail (conj result head))))

=> #{1 2 3 4}

问题是:使用 是否可以达到相同的结果reduce?并使用take-while

编辑:

使用 clojure-1.5.1 和 perforate-0.2.4 对结果进行基准测试

建议的loop-recur实施:

Case:  :loop-recur
Evaluation count : 60 in 60 samples of 1 calls.
             Execution time mean : 1.054975 sec
    Execution time std-deviation : 26.316442 ms
   Execution time lower quantile : 1.026187 sec ( 2.5%)
   Execution time upper quantile : 1.125854 sec (97.5%)

@sw1nnreduce-reduced实现:

Case:  :reduce-reduced
Evaluation count : 120 in 60 samples of 2 calls.
             Execution time mean : 875.091831 ms
    Execution time std-deviation : 19.745142 ms
   Execution time lower quantile : 850.871606 ms ( 2.5%)
   Execution time upper quantile : 921.947759 ms (97.5%)
4

1 回答 1

4

添加了 Clojure 1.5reduced以允许短路减少...

 (reduce (fn [a v] (if-not (a v) (conj a v) (reduced a))) 
         #{} 
         infinite-lazy-sequence)
 => #{1 2 3 4}
于 2013-03-25T22:05:50.850 回答