Pairs

Pairs

Robbert Haarman

2010-12-11


Introduction

A pair consists of two pieces of data put together. These pieces can be of any type; numbers, symbols, and even pairs. A pair is a simple data structure, but it turns out to be very versatile and powerful.

For historical reasons, the head of a pair is called car, and the tail cdr (pronounced “could'r”).


Operations on Pairs


; Create a pair
(cons 1 2) ; => (1 . 2)
(cons 'foo "bar") ; => (foo . "bar")
'(1 . 2) ; => (1 . 2)

; Test if something is a pair
(pair? 1) ; => #f
(pair? (cons 1 2)) ; => #t

; Return parts of a pair
(car (cons 1 2)) ; => 1
(cdr (cons 1 2)) ; => 2

; Set parts of a pair
(define a (cons 1 2))
(set-car! a 'foo) ; a is now (foo . 2)
(set-cdr! a -9) ; a is now (foo . -9)
Valid XHTML 1.1! Valid CSS! Viewable with Any Browser