开发者

Check if item is in a list (Lisp)

What's a simple way to check if an item开发者_StackOverflow 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


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


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.


You can use find:

(find 1 '(5 9 1 2)) ; 1
(find 7 '(5 9 1 2)) ; nil

Consider using :test argument:

(find "a" '("a" "b") :test #'equal)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜