Iterate over a list with a given step


I’m trying to iterate over a list with a given step in clojure.

In python I would have done the following :

xs = list(range(10))

# out: [0, 2, 4, 6, 8]

# out: [1, 3, 5, 7, 9]

I can’t figure out a clojure solution that feels idiomatic.

Here is the best I can think of:

(defn iterate-step-2 [xs]
  (map first (take-while some? (iterate nnext xs))))

(iterate-step-2 (range 10))
; out: (0 2 4 6 8)

(iterate-step-2 (rest (range 10)))
; out: (1 3 5 7 9)

But it’s not as generic (step is not configurable) and as flexible as the python solution. Plus it seems overly complicated.

Is there a better way to do this ?

I see that someone already answered this question of yours on StackOverflow, suggesting take-nth:

user=> (doc take-nth)
([n] [n coll])
  Returns a lazy seq of every nth item in coll.  Returns a stateful
  transducer when no collection is provided.
1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.