Re: newbie exploring better ways
- From: Ken Tilton <kennytilton@xxxxxxxxxxxxx>
- Date: Wed, 30 Jan 2008 01:19:31 -0500
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
.
- Follow-Ups:
- Re: newbie exploring better ways
- From: Rob Warnock
- Re: newbie exploring better ways
- References:
- newbie exploring better ways
- From: vijay
- newbie exploring better ways
- Prev by Date: Re: better way to enumerate
- Next by Date: Re: Announcing a new release of Lisp1 #5
- Previous by thread: Re: newbie exploring better ways
- Next by thread: Re: newbie exploring better ways
- Index(es):
Relevant Pages
|