> Hi,there! > > I need a function that replaces a first found element of list. > like that, > >>(replace-first :a :b [:c :c :a :c :a] > [:c :c :b :c :a] > ~~ > ;replace first :a to :b
An interesting problem for a Sunday morning when I ought to be cleaning the house. :) Here are my (admittedly inexpert) attempts. First, a sort-of-imperative one: (defn rmap-first [key value coll] (let [found (atom false)] (map (fn [x] (if @found x (if (= key x) (do (reset! found true) value) x))) coll))) But that's sort of yucky. So I also did this one, which I sort of like. (defn replace-first ([key value coll] (if coll (if (= key (first coll)) (lazy-cat [value] (next coll)) (lazy-cat [(first coll)] (replace-first key value (next coll))))))) Although I would have liked it better if I didn't have to use a vector for the first argument of lazy-cat. Others will have better solutions, I'm sure. -- You received this message because you are subscribed to the Google Groups "Clojure" group. To post to this group, send email to clojure@googlegroups.com Note that posts from new members are moderated - please be patient with your first post. To unsubscribe from this group, send email to clojure+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/clojure?hl=en