Re: newbie exploring better ways





vijay wrote:
The following function removes only the first occurrence of an element
from a list. Is this very different than how experienced Lispers do
things? The function is part of my homework assignment. However, my
homework is just to write a function that does its job. I am trying to
learn if there are better ways to do it.

(defun remv (item l)
"a function to remove (without modifying the list) the FIRST
occurrence of a given element"
(let ((result-list nil)(flag 0))
(dolist (curr l)
(if (equalp curr item)
( if(equalp flag 1) (push curr result-list) (setq flag 1))
(push curr result-list)))
(reverse result-list)))

Not (remove item l :count 1)? :)

OK, presuming you were under orders to roll your own implementation from more basic stuff, Griff has given you excellent guidance on how to create a neater solution. On a grander level...

I think you asked because you already sensed it could be done more easily. I know the feeling, witness a couple of threads I started here on real-world problems that began "There's gotta be a better way" and like you I was just going from a gut feel in re the contrast between the task and the code I had produced to accomplish it.

So in this case, an experienced lisper would conclude (as you seemed to have) whoa that is too much. How about?:

(loop with nailed
for x in l
if nailed collect x
else if (equalp x item) do (setf nailed t)
else collect x)

But in this case Griff's recursive solution is vastly nicer and more elegant and functional and good with children, you should work that out. Your teacher will know you got help, so show them both versions.

kt


--
http://www.theoryyalgebra.com/

"In the morning, hear the Way;
in the evening, die content!"
-- Confucius
.



Relevant Pages

  • newbie exploring better ways
    ... Is this very different than how experienced Lispers do ... The function is part of my homework assignment. ... (if (equalp curr item) ... (reverse result-list))) ...
    (comp.lang.lisp)
  • Re: newbie exploring better ways
    ... The function is part of my homework assignment. ... (if (equalp curr item) ... Did your teacher suggest EQUALP for the comparison of curr with item? ... EQUALP is not the normal predicate Lisp uses. ...
    (comp.lang.lisp)