nha
nha

Reputation: 18005

Clojure duplicate elements in sequence

I have a simple sequence of arbitrary elements that I would like to reduce over two-by-two.

In order to do that, I generate pairs with the data, but the way I do it is wrong since I need to call a function generating the data twice :

(defn gen-pairs [l]
  (partition 2 (drop 1 (take l (interleave (gen-data) (gen-data))))))

How can I avoid calling gen-data twice (gen-data returns a sequence of items lazily, like range for instance) ?

Upvotes: 1

Views: 407

Answers (1)

Paul Butcher
Paul Butcher

Reputation: 10852

Your question would be clearer if you included an example of what output you wanted, but I think that you're after partition with a step of 1:

user=> (partition 2 1 [1 2 3 4 5 6 7])
((1 2) (2 3) (3 4) (4 5) (5 6) (6 7))

Upvotes: 3

Related Questions