I'm trying to learn lisp and the task I'm trying to conquer is this .
I need to write a recursive function which checks for a given atom that occurs anywhere in an expression.
for example
function search 'a '(b a c)) returns T
search 'a '(k (g c a) h )) returns T
I'm lost please any help would be greatly appreciated
recursion and then some
Re: recursion and then some
You should probably read On Lisp, or ANSI Common Lisp. They (I'm guessing both of them) go over the function in detail. You could also try grepping the source of your favorite Common Lisp implementation for "defun member" to see a real-life example.
But, it's good to figure these things out for yourself, too. Since you didn't post an attempt at solving it, I'm going to show you a simple way to write a recursive list copy function:
Member might work almost the same way, except that it doesn't accumulate a list, and has an extra case for testing EQUALity of a given value.
I think that's enough of a hint; give it a try.
Edit: With regards to atoms, you might want to make sure you're using the right equality predicate.
But, it's good to figure these things out for yourself, too. Since you didn't post an attempt at solving it, I'm going to show you a simple way to write a recursive list copy function:
Code: Select all
CL-USER> (defun my-copy (list &optional acc)
(cond ((null list) (reverse acc))
(t (my-copy (cdr list) (cons (car list) acc)))))
I think that's enough of a hint; give it a try.
Edit: With regards to atoms, you might want to make sure you're using the right equality predicate.
"If you want to improve, be content to be thought foolish and stupid." -Epictetus
Re: recursion and then some
Member doesn't look in sublists, and your copy function only copies the backbone...Duke wrote:You should probably read On Lisp, or ANSI Common Lisp. They (I'm guessing both of them) go over the function in detail. You could also try grepping the source of your favorite Common Lisp implementation for "defun member" to see a real-life example.
dstudentx: given an 'object', check whether it's the one you're looking for, or a cons cell; if it's a cons, "search" its CAR and its CDR for the thing you're looking for.