Note that there are some explanatory texts on larger screens.

plurals
  1. POReduce a lazy sequence like a loop with a condition in Clojure
    primarykey
    data
    text
    <p>I have an infinite lazy sequence that produce a "preamble" and a "pattern repetition", a simple example of this kind of sequence could be implemented in Clojure with:</p> <pre><code>(def infinite-lazy-sequence (lazy-cat [4] (cycle [1 2 3]))) =&gt; (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) </code></pre> <p>I would like to get a <code>set</code> of the elements forming this <code>infinite-lazy-sequence</code>, here is a way to implement it using <code>loop</code>:</p> <pre><code>(loop [[head &amp; tail] infinite-lazy-sequence result #{}] (if (contains? result head) result (recur tail (conj result head)))) =&gt; #{1 2 3 4} </code></pre> <p>Here is the question: is it possible to achieve the same result using <code>reduce</code>? And using <code>take-while</code>?</p> <p><strong>Edit:</strong></p> <p><em>Benchmark results using clojure-1.5.1 and perforate-0.2.4</em></p> <p>proposed <code>loop-recur</code> implementation:</p> <pre><code>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%) </code></pre> <p>@sw1nn <code>reduce-reduced</code> implementation:</p> <pre><code>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%) </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload