Member function with multi-level list in Common Lisp

544 views Asked by At

I'm trying to understand how it works member function with list and list of lists.
Here an example.

(member '(A 6) '((A 7) (B 6) (E 6) (D 5)) :test #'string-equal :key #'second)   

I want to check with the member function if the second argument of the list '(A 6) is member of the second list in input. The answer should be

true

but I'm doing something wrong, because Common Lisp reply:

 Error: Cannot coerce (A 6) to type STRING. 

So how can I take the second argument from the first list? Thank you for the help.

1

There are 1 answers

0
sds On BEST ANSWER

What you are missing is that the :key argument is not applied to the first argument of member.

Another thing is that second will return the number, not the symbol.

Thus:

(member 'A '((A 7) (B 6) (E 6) (D 5)) :test #'string-equal :key #'first)
==> ((A 7) (B 6) (E 6) (D 5))
(member 'C '((A 7) (B 6) (E 6) (D 5)) :test #'string-equal :key #'first)
==> NIL
(member 'E '((A 7) (B 6) (E 6) (D 5)) :test #'string-equal :key #'first)
==> ((E 6) (D 5))

Note that the return value is the tail, not the matched list element. This is to allow the use of member as a predicate, i.e., to distinguish between finding nil and finding nothing:

(member nil '(1 2 nil 3))
==> (NIL 3)
(find nil '(1 2 nil 3))
==> NIL
(find t '(1 2 nil 3))
==> NIL