Hi,
how can I make a Lisp program that checks if a character, string or number is in a list?
(list-contains '(1 a 2 d 2 5) 'a) => T
(list-contains '(1 a 2 d 2 5) 'x) => NIL
Hi,
how can I make a Lisp program that checks if a character, string or number is in a list?
(list-contains '(1 a 2 d 2 5) 'a) => T
(list-contains '(1 a 2 d 2 5) 'x) => NIL
You can use (find x the-list)
which returns x if x is in the list or NIL if it is not.
(find 'a '(1 a 2 d 2 5)) ; A
(find 'x '(1 a 2 d 2 5)) ; NIL
Since this is homework, your professor would probably like to see you implement an algorithm. Try this:
Greg's solution is what you should implement. But I want to add that, in case you hadn't head of it, The Little Schemer is a great introduction to this sort of thing. Try to get a copy, or even just open the preview up in Google Books and search for "member?". They do what you'd expect (that is, check if car is equal, recur on cdr if it isn't) but they trace it and ask you questions at each step.
It's not a very long or expensive book, but once you read it, you will have a natural feel for how to approach this sort of problem. They all boil down to the same thing, which for lists amounts to asking if we've hit the empty list yet, and if not, either doing something with car or recurring on cdr.