Skip to main content

adjoin

adjoin Function

Syntax:

adjoin item list &key key test test-not → new-list

Arguments and Values:

item—an object.

list—a proper list.

test—a designator for a function of two arguments that returns a generalized boolean. test-not—a designator for a function of two arguments that returns a generalized boolean. key—a designator for a function of one argument, or nil.

new-list—a list.

Description:

Tests whether item is the same as an existing element of list. If the item is not an existing element, adjoin adds it to list (as if by cons) and returns the resulting list; otherwise, nothing is added and the original list is returned.

The test, test-not, and key affect how it is determined whether item is the same as an element of list. For details, see Section 17.2.1 (Satisfying a Two-Argument Test).

Examples:

(setq slist ’()) → NIL 
(adjoin ’a slist)(A)
slist → NIL
(setq slist (adjoin(test-item 1) slist))((TEST-ITEM 1))
(adjoin(test-item 1) slist)((TEST-ITEM 1) (TEST-ITEM 1))
(adjoin(test-item 1) slist :test ’equal)((TEST-ITEM 1))
(adjoin(new-test-item 1) slist :key #’cadr)((TEST-ITEM 1))
(adjoin(new-test-item 1) slist)((NEW-TEST-ITEM 1) (TEST-ITEM 1))

Exceptional Situations:

Should be prepared to signal an error of type type-error if list is not a proper list.

See Also:

pushnew, Section 3.6 (Traversal Rules and Side Effects)

Notes:

The :test-not parameter is deprecated.

(adjoin item list :key fn)

(if (member (fn item) list :key fn) list (cons item list))

Expanded Reference: adjoin

Basic usage

adjoin adds an item to a list only if it is not already present. By default, it uses eql for comparison.

(adjoin 'a '(b c d))
=> (A B C D)

(adjoin 'b '(b c d))
=> (B C D)

Non-destructive behavior

adjoin does not modify the original list. It returns a new list when the item is added.

(let ((lst '(1 2 3)))
(adjoin 4 lst)
lst)
=> (1 2 3)

Using :test for custom comparison

By default, adjoin uses eql, which does not compare lists by structure. Use :test #'equal to compare by value.

(adjoin '(a b) '((a b) (c d)))
=> ((A B) (A B) (C D))

(adjoin '(a b) '((a b) (c d)) :test #'equal)
=> ((A B) (C D))

Using :key to compare by a component

The :key function extracts the part of each element to compare against the item (after applying :key to the item as well).

(adjoin '(name "Bob") '((name "Alice") (age 30)) :key #'car)
=> ((NAME "Alice") (AGE 30))

(adjoin '(email "bob@test.com") '((name "Alice") (age 30)) :key #'car)
=> ((EMAIL "bob@test.com") (NAME "Alice") (AGE 30))

Building a set from a sequence

adjoin can be used with reduce to build a set with no duplicates.

(reduce (lambda (lst item) (adjoin item lst))
'(a b a c b d a)
:initial-value '())
=> (D C B A)