mapsplice

utilities — cgrand, 25 March 2009 @ 22 h 11 min

I needed to update a seq as follows: apply a given function to items at specified indices and insert the result (a seq) in place.
My first laborious attempt involved extracting subseqs of untouched items, mapping the function on the remaining items then joining everything back. Bleh! (Really, I don’t like indices but this time I haven’t found a way to work around.)
I was sad when, suddenly, I found this shortest solution:

(defn mapsplice [f coll indices]
  (let [need-splice (map (set indices) (iterate inc 0))]
    (mapcat #(if %2 (f %1) [%1]) coll need-splice)))
;; (mapsplice #(repeat % %) (range 10) [7 3])
;; (0 1 2 3 3 3 4 5 6 7 7 7 7 7 7 7 8 9)
(c) 2017 Clojure and me | powered by WordPress with Barecity