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

clojure, functional-programming

Solution

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)

Problem

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)

Original source