Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if item is in a list (Lisp)

What's a simple way to check if an item is in a list?

Something like

(in item list) 

might return true if item=1 and list=(5 9 1 2) and false if item=7

like image 788
Jeff Avatar asked May 26 '11 20:05

Jeff


People also ask

Is a list a Lisp?

The list function is rather used for creating lists in LISP. The list function can take any number of arguments and as it is a function, it evaluates its arguments. The first and rest functions give the first element and the rest part of a list. The following examples demonstrate the concepts.

Is nil a list in Lisp?

The symbol nil is an atom and is also a list; it is the only Lisp object that is both.

What does member do in Lisp?

Simplified Common Lisp reference - member. MEMBER function searches a list for the first occurrence of an element (item) satisfying the test. Return value is tail of the list starting from found element or NIL when item is not found. See also MEMBER-IF, POSITION, POSITION-IF, FIND and FIND-IF.


2 Answers

Use MEMBER to test whether an item is in a list:

(member 1 '(5 9 1 2))  ; (1 2) 

Unlike FIND, it is also able to test whether NIL is in the list.

like image 27
Terje Norderhaug Avatar answered Sep 23 '22 13:09

Terje Norderhaug


Common Lisp

FIND is not a good idea:

> (find nil '(nil nil)) NIL 

Above would mean that NIL is not in the list (NIL NIL) - which is wrong.

The purpose of FIND is not to check for membership, but to find an element, which satisfies a test (in the above example the test function is the usual default EQL). FIND returns such an element.

Use MEMBER:

> (member nil '(nil nil)) (NIL NIL)  ; everything non-NIL is true 

or POSITION:

> (numberp (position nil '())) NIL 
like image 109
Rainer Joswig Avatar answered Sep 26 '22 13:09

Rainer Joswig