使用Clojure中的条件减少类似循环的延迟序列

时间:2013-03-25 21:41:45

标签: clojure

我有一个无限的懒惰序列,产生“前导码”和“模式重复”,这种序列的一个简单例子可以在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的{​​{1}}个元素,以下是使用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

修改

使用clojure-1.5.1和perforate-0.2.4的基准测试结果

提议take-while实施:

loop-recur

@ sw1nn 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%) 实施:

reduce-reduced

1 个答案:

答案 0 :(得分:4)

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

 (reduce (fn [a v] (if-not (a v) (conj a v) (reduced a))) 
         #{} 
         infinite-lazy-sequence)
 => #{1 2 3 4}