help-gnu-emacs
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

"assoc" for returning ALL associations for a given key


From: florian
Subject: "assoc" for returning ALL associations for a given key
Date: Tue, 5 May 2009 01:59:48 -0700 (PDT)
User-agent: G2/1.0

I somehow suspect this question must have been discussed dozens of
times before, but well ...

As is well known, association lists differ from hashes in that the
same key can occur several times, and (assoc KEY ALIST) will return
only the first such occurrence.

Consequently, a convenient method for changing the value of an
association is to simply conse the new association to the front of the
alist, which will make any old associations with the same key
"invisible" (even if that feels kind of messy to me).

I am not wondering, however, whether it is generally better to use
hashes; rather, I am musing about whether the fact that association
lists may contain the same key several times could be seen as an
advantage: An alist could be the obvious place to store information
such as, e.g.,  "In which directories do I have a file with basename
X?", where X would be the key, and the directories, the values.

I have found no function comparable to assoc to cater for such a need,
and have thus written one for myself:

    (defun assocs (key alist)
      "Like `assoc', but return all elements of ALIST whose car is
`equal' to KEY.
In other words, return a subset of ALIST."
      (delq nil
            (mapcar '(lambda (cons-cell)
                       (if (equal (car cons-cell) key)
                           cons-cell))
                    alist)))

But I am wondering whether that would have been necessary - perhaps I
am overlooking something? Otherwise, would anybody care to comment
about the efficiency of the above function?

Many thanks for your thoughts!

Florian


reply via email to

[Prev in Thread] Current Thread [Next in Thread]