views:

62

answers:

3

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

+1  A: 

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
sepp2k
+3  A: 

Since this is homework, your professor would probably like to see you implement an algorithm. Try this:

  1. Take the car of the list and compare it against the input symbol.
  2. If it's the same, return true; you're done.
  3. If it's empty, return false; you're done.
  4. 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 Harman
A: 

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.

John C