From: Barry Margolin
Subject: Re: intersection: noncommutative: can be relied upon?
Date:
Message-ID: <622nfh$ogl@tools.bbnplanet.com>

In article <·············@WINTERMUTE.eagle>,
SDS <···········@cctrading.com> wrote:
>Neither CLtL2 nor CLHS specify this:
> (intersection '(a b) '((a . 1) (b . 2) (c . 3)) :test #'eq :key
> (lambda (x) (if (consp x) (car x) x)))
> ==> (a b)
> (intersection '((a . 1) (b . 2) (c . 3)) '(a b) :test #'eq :key
> (lambda (x) (if (consp x) (car x) x)))
> ==> ((a . 1) (b . 2))
>
>Can I assume that intersection takes the elements from the first list?
You can assume that *this* implementation of INTERSECTION takes the
elements from the first list. And you might even be right.
>(It is specified for nintersection, but what about intersection?)
I don't see it specified for NINTERSECTION. It says that it *may* destroy
the first argument. But it doesn't say where it gets the elements from.
So the following could happen:
(setq arg1 (list a b))
(setq arg2 (list '(a . 1) '(b . 2) '(c . 3)))
(setq result (nintersection arg1 arg2)) => ((a . 1) (b . 2))
arg1 => ((a . 1) (b . 2))
(eq (car arg1) (car arg2)) => T
What this possible implementation did was use the list backbone from arg1,
but filled it in with the matching elements from arg2.
>Is intersection the proper tool to extract subsets matching on a key?
>(Like in the second call above, a subset of the alist is extracted).
>Of course, there are many ways to extract subsets, e.g.,
> (mapcon (lambda (x) (if (member (caar x) '(a b)) (list (car x)) nil))
> '((a . 1) (b . 2) (c . 3)))
> ==> ((a . 1) (b . 2))
>What would the gurus think to be "the best way"?
The REMOVE/DELETE family of functions are usually used for this:
(remove '(a b) '((a . 1) (b . 2) (c . 3)) :key #'car
:test #'(lambda (list element) (not (member element list))))
You can't just use :TEST #'MEMBER because the arguments are in the wrong
order.
(remove-if #'(lambda (element) (not (member element '(a b))))
'((a . 1) (b . 2) (c . 3)) :key #'car)
--
Barry Margolin, ······@bbnplanet.com
GTE Internetworking, Powered by BBN, Cambridge, MA
Support the anti-spam movement; see <http://www.cauce.org/>
Please don't send technical questions directly to me, post them to newsgroups.