Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Neat way to apply a function to every nth element of a sequence?

What's a neat way to map a function to every nth element in a sequence ? Something like (map-every-nth fn coll n), so that it would return the original sequence with only every nth element transformed, e.g. (map-every-nth inc (range 16) 4) would return (0 1 2 4 4 5 6 8 8 9 10 12 12 13 14 16)

like image 407
Hendekagon Avatar asked Apr 26 '12 01:04

Hendekagon


1 Answers

Try this:

(defn map-every-nth [f coll n]
  (map-indexed #(if (zero? (mod (inc %1) n)) (f %2) %2) coll))

(map-every-nth inc (range 16) 4)
> (0 1 2 4 4 5 6 8 8 9 10 12 12 13 14 16)
like image 134
Óscar López Avatar answered Oct 04 '22 20:10

Óscar López