Reputation: 1554
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
Upvotes: 4
Views: 11269
Reputation: 2514
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
However,
(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.
Upvotes: 0
Reputation: 2259
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.
Upvotes: 0
Reputation: 7111
Since this is homework, your professor would probably like to see you implement an algorithm. Try this:
Upvotes: 6
Reputation: 370172
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
Upvotes: 14