Lisp list-contains program
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:
- Take the car of the list and compare it against the input symbol.
- If it's the same, return true; you're done.
- If it's empty, return false; you're done.
- Recurse back to #1, using the cdr of the list. (Here, implied that the car was not empty and was not the comparison symbol)
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.
I recommend you the position function. It returns the position of the element in the list (the first position is 0) or NIL if it is not.
(position 'a '(1 a 2 d 2 5)) ; 1 (position 'x '(1 a 2 d 2 5)) ; NIL
position has an advantage over find. You can know if the symbol 'NIL in a list.
(position 'NIL '(1 a NIL d 2 5)) ; 2 (position 'NIL '(1 a 2 d 2 5)) ; NIL
(find 'NIL '(1 a NIL d 2 5)) ; NIL (find 'NIL '(1 a 2 d 2 5)) ; NIL
So with find there is no way to distinguish one case from the other.