Lisp list contains program

how can I create 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

+3
source share
4 answers

You can use (find x the-list)that 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
+12
source

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

  • Take the car from the list and compare it with the input symbol.
  • If this is the same, return true; you are done.
  • If it is empty, return false; you are done.
  • Return to # 1 using the cdr list. (It was understood here that the car was not empty and was not a symbol of comparison)
+7

Greg - , . , , , The Little Schemer - . Google "member?". , ( , , , cdr, ), .

, , , . , , , , - , cdr.

0

I recommend you the function position. 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  



positionhas an advantage over find. You can find out if there is a character 'NILin the 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 the help findit is impossible to distinguish one case from another.

0
source

Source: https://habr.com/ru/post/1753602/


All Articles