Skip to main content

acons

acons Function

Syntax:

acons key datum alist → new-alist

Arguments and Values:

key—an object.

datum—an object.

alist—an association list.

new-alist—an association list.

Description:

Creates a fresh cons, the cdr of which is alist and the car of which is another fresh cons, the car of which is key and the cdr of which is datum.

Examples:

(setq alist ’()) → NIL 
(acons 1 "one" alist)((1 . "one"))
alist → NIL
(setq alist (acons 1 "one" (acons 2 "two" alist)))((1 . "one") (2 . "two")) (assoc 1 alist)(1 . "one")
(setq alist (acons 1 "uno" alist))((1 . "uno") (1 . "one") (2 . "two"))
(assoc 1 alist)(1 . "uno")

See Also:

assoc, pairlis

Notes:

(acons key datum alist) (cons (cons key datum) alist)

Expanded Reference: acons

Basic usage

acons adds a new key-value pair to the front of an association list. It is equivalent to (cons (cons key datum) alist).

(acons 'name "Alice" '())
=> ((NAME . "Alice"))

(acons 'age 30 '((name . "Alice")))
=> ((AGE . 30) (NAME . "Alice"))

Building an alist incrementally

Since acons does not modify the original alist, you must capture the return value to build up the list.

(defvar *settings* '())

(setq *settings* (acons 'color 'red *settings*))
=> ((COLOR . RED))

(setq *settings* (acons 'size 'large *settings*))
=> ((SIZE . LARGE) (COLOR . RED))

(setq *settings* (acons 'weight 10 *settings*))
=> ((WEIGHT . 10) (SIZE . LARGE) (COLOR . RED))

Shadowing previous entries

Adding a duplicate key shadows the earlier entry. assoc finds the first match, so the new value takes precedence.

(let ((alist (acons 'x 1 '())))
(setq alist (acons 'x 2 alist))
(assoc 'x alist))
=> (X . 2)

Non-destructive behavior

The original alist is not modified by acons.

(let ((original '((a . 1) (b . 2))))
(acons 'c 3 original)
original)
=> ((A . 1) (B . 2))

Equivalence to cons of cons

acons is defined as a convenience shorthand.

(equal (acons 'k 'v '((a . 1)))
(cons (cons 'k 'v) '((a . 1))))
=> T