You're scanning the list twice, first to find the element position, and then
to do the split; it's better to do it all at once. Here's a simple version:
(defn replace-first [from to in]
(cond (empty? in) in
(= (first in) from) (cons to (rest in))
:else (cons (first in) (replace-first from to (rest in)))))
And here's one rewritten to take advantage of tail recursion:
(defn replace-first [from to in & prefix]
(cond (empty? in) prefix
(= (first in) from) (concat prefix (list to) (rest in))
:else (recur from to (rest in) (concat prefix (list (first
in)))))))
But there are no doubt better ways to do it, probably built in or in
clojure.core.
On Sat, May 8, 2010 at 4:24 AM, ken.coba <[email protected]> wrote:
> 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
>
> and my code is as follows.
> ---code begin------------------------------------------
> (use '[clojure.contrib.seq-utils])
>
> (defn position [x coll]
> (first (positions #(= x %) coll)))
>
> (defn replace-first [s r coll]
> (let [idx (position s coll)
> splitted (split-at idx coll)]
> (concat (first splitted) (list r) (rest (fnext splitted)))))
>
> ---code end------------------------------------------
>
> I'd like to see how the replase-first could be improved,
> especially concatination of elements.
>
> Thanks for your insights.
>
> Kenichi Kobayashi
>
> --
> You received this message because you are subscribed to the Google
> Groups "Clojure" group.
> To post to this group, send email to [email protected]
> Note that posts from new members are moderated - please be patient with
> your first post.
> To unsubscribe from this group, send email to
> [email protected]<clojure%[email protected]>
> For more options, visit this group at
> http://groups.google.com/group/clojure?hl=en
--
Mark J. Reed <[email protected]>
--
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to [email protected]
Note that posts from new members are moderated - please be patient with your
first post.
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en