Utilities for manipulating association lists.
(defvar *person*
'(("name" . "Eitaro") ("email" . "[email protected]")))
(aget *person* "name")
;=> "Eitaro"
(aget *person* "address")
;=> NIL
(aget *person* "address" "Tokyo, Japan")
;=> "Tokyo, Japan"
(setf (aget *person* "name") "Eitaro Fukamachi")
*person*
;=> (("name" . "Eitaro Fukamachi") ("email" . "[email protected]"))
The macro with-keys
is the alist equivalent of with-slots
.
(with-keys
("name" (loc "location") (time "time" 2024))
(list (cons "name" "eitaro") (cons "location" "vienna"))
(declare (string name))
(setf loc (string-upcase loc))
(format nil "Hi, ~a in ~a around ~a!" name loc time))
;; => "Hi, eitaro in VIENNA around 2024!"
The first parameter is a list of keys that with-keys
will reference in the alist
provided in the second parameter. With-keys
will attempt to convert each
key into a symbol, binding the alist value to it during body execution.
If you don't want with-keys
to guess the symbol for a key, supply a list -
(symbol key)
- in place of the key, as in (loc "location")
above.
If the key is a number, you have to supply a symbol name since common lisp
symbols can not consist of only numbers.
If you want to supply a default value, you have to supply a list -
(symbol key default)
- in place of the key, as in (time "time" 2024)
.
Code and documentation adapted from cl-hash-util.
(defvar *person*
'(("name" . "Eitaro") ("email" . "[email protected]")))
(remove-from-alist *person* "name")
;=> (("email" . "[email protected]"))
;; Destructive version
(delete-from-alist *person* "name")
;=> (("email" . "[email protected]"))
(defvar *person*
'(("name" . "Eitaro") ("email" . "[email protected]")))
(alist-plist *person*)
;=> (:NAME "Eitaro" :EMAIL "[email protected]")
(plist-alist '(:name "Eitaro" :email "[email protected]"))
;=> (("name" . "Eitaro") ("email" . "[email protected]"))
(defvar *person*
'(("name" . "Eitaro") ("email" . "[email protected]")))
(alist-hash *person*)
;=> #<HASH-TABLE :TEST EQUAL :COUNT 2 {1004329443}>
(hash-alist *)
;=> (("name" . "Eitaro") ("email" . "[email protected]"))
(defvar *person*
'(("name" . "Eitaro") ("email" . "[email protected]")))
(alist-keys *person*)
;=> ("name" "email")
(alist-values *person*)
;=> ("Eitaro" "[email protected]")
(alistp '(("name" . "Eitaro") ("email" . "[email protected]")))
;=> T
(alistp 1)
;=> NIL
(alistp nil)
;=> T
;; Type: alist is also available
(typep '(("name" . "Eitaro") ("email" . "[email protected]")) 'alist)
;=> T
(alist= '(("name" . "Eitaro") ("email" . "[email protected]"))
'(("email" . "[email protected]") ("name" . "Eitaro")))
;=> T
(ql:quickload :assoc-utils)
- Eitaro Fukamachi ([email protected])
Assoc-Utils is free and unencumbered software released into the public domain.