Re: Hints on recursion
- From: Pascal Bourguignon <spam@xxxxxxxxxxxxxxxx>
- Date: Wed, 30 Nov 2005 06:23:55 +0100
"mpeever" <mpeever@xxxxxxxxx> writes:
> OK, so I may be breaking netiquette, posting when I've not been here a
> day, but I had to throw this out.
>
> I'm a newbie, my Lisp sucks. But I did come up with what i think might
> be a valid solution, although I did use cons:
>
> 1. return true when the element appears in the first two places in the
> list
> 2. return false if the list has fewer than 2 elements
> 3. delete any non-matching elements from the list and recurse
>
> My version looks like this, but someone who actually knows what they're
> doing could do it better, I'm sure:
>
> (defun find-twice (a lst)
> (cond ((and (eq (first lst) a) (eq (first (rest lst)) a)) lst)
> ((or (eq (first lst) nil) (eq (rest lst) nil)) nil)
> ((not (eq (first lst) a)) (find-twice a (rest lst)))
> (t (find-twice a ((first lst) . (cdr (rest lst)))))))
You need to write CONS instead of the dot:
(cons (first lst) (cdr (rest lst)))
but otherwise it's a good solution. Well done!
Since AND and NOT is not allowed in point 1, you'd have to write:
(cond (a b)) instead of (and a b)
(null x) instead of (not x)
but this is a silly requirement...
--
__Pascal Bourguignon__ http://www.informatimago.com/
Wanna go outside.
Oh, no! Help! I got outside!
Let me back inside!
.
- References:
- Hints on recursion
- From: zion_zii
- Re: Hints on recursion
- From: mpeever
- Hints on recursion
- Prev by Date: Re: Hints on recursion
- Next by Date: Re: OT to the extreme
- Previous by thread: Re: Hints on recursion
- Next by thread: Re: Hints on recursion
- Index(es):
Relevant Pages
|