Association list utilities
Lassi Kortela 10 Jun 2020 08:24 UTC
> > If you need `cdr' after `assoc' very often, I'd use a helper procedure
> > like this one:
>
> This breaks the correctnsess of assoc: That #f is always unambigous as
> "not found". That’s why I want to preserve the behaviour and only unpack
> in the final processing.
>
> Yes, you are right in case `#f' is a valid value in your association list.
> If this is the case, you can code it in a data-driven style with SRFI 189:
All of us have probably written (and re-written and
re-re-...-re-written) our own alist utilities. It would be nice to
decide on a canonical set and codify them in an alist SRFI.
SLIB has some:
<http://people.csail.mit.edu/jaffer/slib/Association-Lists.html#Association-Lists>
I use the following:
- `assoc?` -- (cadr (assoc key alist)) or #f if not found
- `assoc1` -- (cadr (assoc key alist)) or raise exception if not found
- `assoc*` -- (cdr (assoc key alist) or '() if not found
- `assoc+` -- (cdr (assoc key alist) or raise exception if not found
The single-value procedures `assoc?` and `assoc1` raise an exception if
the association pair isn't a proper list of length 2.
There's also the further question of whether these should check the
entire list for duplicate keys or not.
Also both (key value) and (key . value) style pairs are useful. Consing
dots are a bother to type in files, especially files that need to make
sense to people who are not Lisp fans. Hence it's good to be able to use
(key value) for external data and read it in as-is without converting
all (key value) alists to (key . value).
Many nuances to think about.