duelin markers
duelin markers

Reputation: 574

Is there a better way to map all but the first item?

I feel like there must be a cleaner way to do this, but I don't see it.

(defn map-rest
  "Passes through the first item in coll intact. Maps the rest with f."
  [f coll]
  (concat (list (first coll)) (map f (rest coll))))

Upvotes: 11

Views: 262

Answers (1)

noahlz
noahlz

Reputation: 10311

Destructuring and using cons instead of concat:

(defn map-rest [f [fst & rst]] (cons fst (map f rst)))

REPL output:

user=> (map-rest inc [1 2 3 4 5])
(1 3 4 5 6)

Upvotes: 25

Related Questions