Warm tip: This article is reproduced from serverfault.com, please click

Iterate over a list with a given step in clojure

发布于 2020-11-28 02:53:53

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))

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

xs[1::2]
# 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 ?

Questioner
Tewfik
Viewed
0
Gwang-Jin Kim 2020-11-28 11:48:35
;; equivalent to Python's your_seq[1:7:2] would be:
(->> your-seq (drop 1) (take 7) (take-nth 2))

;; equivalent to Python's your_seq[::2] would be:
(->> your-seq (take-nth 2))

;; equivalent to Python's your_seq[2:4:-3] would be:
(->> your-seq (take 4) (drop 2) (reverse) (take-nth 3))

;; equivalent to Python's your_seq[2:-4:-1]:
(->> your-seq (take (+ 1 (- (length your-seq) 4))) (drop 2) (reverse))