Check if item is in a list (Lisp)

走远了吗. 提交于 2019-12-21 03:09:13

问题


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


回答1:


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



回答2:


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.




回答3:


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)


来源:https://stackoverflow.com/questions/6144435/check-if-item-is-in-a-list-lisp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!