how to test whether one list is a member of another

后端 未结 2 639
甜味超标
甜味超标 2021-01-18 14:45

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 t

2条回答
  •  梦毁少年i
    2021-01-18 15:30

    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
    

    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
    

提交回复
热议问题