Skip to main content

cons

cons Function

Syntax:

cons object-1 object-2 → cons

Arguments and Values:

object-1—an object.

object-2—an object.

cons—a cons.

Description:

Creates a fresh cons, the car of which is object-1 and the cdr of which is object-2.

Examples:

(cons 1 2)(1 . 2) 
(cons 1 nil)(1)
(cons nil 2)(NIL . 2)
(cons nil nil)(NIL)
(cons 1 (cons 2 (cons 3 (cons 4 nil))))(1 2 3 4)
(cons ’a ’b)(A . B)
(cons ’a (cons ’b (cons ’c ’())))(A B C)
(cons ’a ’(b c d))(A B C D)

See Also:

list

Notes:

If object-2 is a list, cons can be thought of as producing a new list which is like it but has object-1 prepended.

Expanded Reference: cons

Creating a dotted pair

cons creates a new cons cell with two components: the car and the cdr.

(cons 'a 'b)
=> (A . B)

Building a list element by element

When the second argument is a list (or NIL), cons prepends the first argument to that list.

(cons 1 nil)
=> (1)

(cons 1 '(2 3 4))
=> (1 2 3 4)

Building a list from scratch

You can nest cons calls to construct a proper list, terminating with NIL.

(cons 'a (cons 'b (cons 'c nil)))
=> (A B C)

Cons cells hold any types of objects

The car and cdr of a cons can be any Lisp object, including other cons cells, strings, numbers, or symbols.

(cons "hello" 42)
=> ("hello" . 42)

(cons '(1 2) '(3 4))
=> ((1 2) 3 4)

Using cons to prepend to an association list

A common pattern is using cons to add a new key-value pair to an alist.

(defvar *settings* '((:width . 80) (:height . 24)))

(setq *settings* (cons '(:color . :blue) *settings*))
=> ((:COLOR . :BLUE) (:WIDTH . 80) (:HEIGHT . 24))