clojure - idiomatic way to only update the first elem matching a pred in a coll -


i have seq, (def coll '([:a 20] [:b 30] [:c 50] [:d 90]))

i want iterate through seq, , modify first element matches predicate.

the predicate (def pred (fn [[a b]] (> b 30)))

(f pred (fn [[a b]] [a (+ b 2)]) coll) => ([:a 20] [:b 30] [:c 52] [:d 90])

f fn want, takes pred, , fn apply first elem matches pred. rest of elems not modified , returned in seq.

what idiomatic way above?

one possible way split collection split-with, apply function f first element of second collection returned split-with, , concat elements again.

(defn apply-to-first [pred f coll]     (let [[h t] (split-with (complement pred) coll)]         (concat h (list (f (first t))) (rest t)))) 

note pred function in example should this:

(def pred #(> (second %) 30)) 

Comments

Popular posts from this blog

linux - xterm copying to CLIPBOARD using copy-selection causes automatic updating of CLIPBOARD upon mouse selection -

c++ - qgraphicsview horizontal scrolling always has a vertical delta -