如何测试一个列表是否是另一个列表的成员 [英] how to test whether one list is a member of another

查看:85
本文介绍了如何测试一个列表是否是另一个列表的成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有两个列表,((1 2 3))(((1 2 3)) ((4 5))).我想知道第一个列表是否是第二个列表的成员.我尝试使用subsetp,但此查询未返回true.我该怎么做?

Lets say I have two lists, ((1 2 3)) and (((1 2 3)) ((4 5))). I want to be able to tell if the first list is a member of the second list. I have tried to use subsetp, but it does not return true for this query. How can I accomplish this?

推荐答案

如Rainer Joswig 注释中提到的,您不是在检查子集,而是在检查成员,您可以使用适当命名的 member 函数. Member返回一个广义布尔值,即nil为false,某些东西(不一定是t)非-nil是true.具体来说,如果元素是列表的成员,则member返回列表的尾部,其第一个元素是该元素.

As Rainer Joswig mentioned in the comments, you're not checking for subsets, but for members, which you can do using the aptly named member function. Member returns a generalized boolean, i.e., nil for false, and something, not necessarily t, non-nil for true. Specifically, if an element is a member of the list, member returns the tail of the list whose first element is the element.

CL-USER> (member 3 '(1 2 3 4 5))
(3 4 5)
CL-USER> (member 7 '(1 2 3 4 5))
NIL

当然,当检查列表中的成员资格时,存在一个问题,即如何将给定项目与列表中的元素进行比较. Member的默认比较是eql,它适用于数字之类的事情,如上面的示例所示.但是,对于您的情况,您可能要使用equal进行测试,因为((1 2 3))可能与(((1 2 3)) ((4 5)))的第一个元素不是 same 对象:

Of course, when checking membership in a list, there's a question of how to compare the given item with the elements of the list. Member's default comparison is eql, which works on things like numbers, as shown in the example above. For your case, however, you probably want to test with equal, since ((1 2 3)) might not be the same object as the first element of (((1 2 3)) ((4 5))):

CL-USER> (member '((1 2 3)) '(((1 2 3)) ((4 5))))
NIL
CL-USER> (member '((1 2 3)) '(((1 2 3)) ((4 5))) :test 'equal)
(((1 2 3)) ((4 5)))
CL-USER> (member '((4 5)) '(((1 2 3)) ((4 5))) :test 'equal)
(((4 5)))
CL-USER> (member '((1 2 4)) '(((1 2 3)) ((4 5))) :test 'equal)
NIL

这篇关于如何测试一个列表是否是另一个列表的成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆