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

Answers


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:

  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'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

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.


Need Your Help

SVProgressHUD - Showing / Hiding the control quickly causes it to not come up the next time showWithStatus is called

ios svprogresshud

I have some source code below which will reproduce this. Calling showWithStatus and dismiss before the HUD has a chance to present itself is causing the control to not show the next time showWithSt...

How do I use PIA to open an Excel workbook and save the first sheet to a text file?

.net excel office-interop

I'm not too familiar w/ the PIA assembly's for Office interop (Office 2007) and via .NET/C#, I need to open a workbook and save the first sheet within it as a tab delimited text file. Can someone