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
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.
The symbol nil is an atom and is also a list; it is the only Lisp object that is both.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With