Well obviously if you can get something to be tail-recursive you won't have
the stack overflows, and the thing in your code that prevents tail recursion
is having to cons the result of the recursive call. So let's try this:

(defn remove-first
  [syb lst]
  (let [[before after]
          (loop [b [] a lst]
            (if (empty? lst)
              [b a]
              (if (= syb (first a))
                [b (rest a)]
                (recur (cons (first a) b) (rest a)))))]
   (concat (reverse before) after)))

user=> (remove-first 4 '(1 5 3 4 2 6 674 4 2))
(1 5 3 2 6 674 4 2)

I'm interested if somebody comes up with something more efficient, i.e. that
doesn't require the reversal.

Gary

On Sat, Jul 24, 2010 at 11:41 AM, nickikt <nick...@gmail.com> wrote:

> Hallo all,
>
> I'm working trough Essentials of Programming Languages. I'm trying to
> right a function like this one:
>
> (defn scheme-remove-first [syb lst]
>  (if (empty? lst)
>    '()
>    (if (= (first lst) syb)
>      (rest lst)
>      (cons (first lst) (scheme-remove-first syb (rest lst))))))
>
> in a idiomatic clojure way (this is just a scheme to clojure 1:1
> version). I don't like that this function produces stack overflows.
>
> I tried some stuff but I it (almost) semantically correct working but
> I didn't like my code. Can anyone come up with a good version?
>
> --
> 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<clojure%2bunsubscr...@googlegroups.com>
> For more options, visit this group at
> http://groups.google.com/group/clojure?hl=en




-- 
Gary Fredericks
(660)-623-1095
fredericksg...@gmail.com
www.gfredericks.com

-- 
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

Reply via email to