Skip to content

Scheme: Understanding cons, car, cdr #16

@hungle00

Description

@hungle00

What are cons, car, cdr?

In most Lisp languages like Scheme, car, cdr, and cons are the most important functions.
The cons function is used to construct pairs, it accepts any two values. The car and cdr are used to access data and return accordingly the first and second element from a pair.

(define x (cons 1 2))
;; => (1 . 2)
(car x) ;; => 1
(cdr x) ;; => 2

A list can be defined recursively as either the empty list () or a pair whose second element (cdr) is a list. For example:
'() means ()
(cons 1 '()) means (1)
(cons 1 (cons 2 (cons 3 '()))) means (1 2 3)

Scheme provides list function to build a List, using pairs under the hood:

(list 1 2 3 4)
;; or shortend
'(1 2 3 4)

cons function also can accept a list as a second argument, so appending value to the list can be written as:

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

The cdr function returns the second element of the pair which in the case of lists is the list’s tail. So applying the car and cdr function we can access any element of the list:

(define nums (list 1 2 3 4))
(car nums) ;;=> 1
(car (cdr nums))  ;; => 2

Scheme: Use of car, cdr

As we know, functional programming contains no assignment statements, so variables, once given a value, can not change. It means we can not use a loop over the list (because loops are based on mutating one variable).
Other sides, from the previous part, we know that we can access any element of the list by combining 2 functions car - cdr.
So instead of a loop, we use a recursive with car - cdr to work with List:

For example, count the number of items in List:

(define nums (list 2 4 5 7 8))

(define (length items)
  (if (null? items)
    0
    (+ 1 (length (cdr items)))))

(length nums)

In the next example, append function takes two lists as arguments and returns a new list that contains all elements of two input lists

(define (append list1 list2)
  (if (null? list1)
    list2
    (cons (car list1)
          (append (cdr list1) list2))))

(append (list 1 3 5) (list 2 4 8))

More resources

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions