Google News
logo
Lisp - Interview Questions
What is the purpose of the "car" and "cdr" functions in Lisp?
In Lisp, the functions `car` and `cdr` are used to extract components from lists, which are fundamental data structures. These functions operate on pairs, also known as cons cells, which are the building blocks of Lisp lists.

Here's an explanation of the purpose of the `car` and `cdr` functions:

1. `car`:
   * The `car` function takes a pair or a list as its argument and returns the first element of that pair or list.
   * If the argument is a non-empty list, `car` retrieves the head or the first element of the list.
   * If the argument is a pair (cons cell), `car` retrieves the first element of that pair.

2. `cdr`:
   * The `cdr` function takes a pair or a list as its argument and returns the rest of the elements after the first element.
   * If the argument is a non-empty list, `cdr` retrieves the tail or the sublist excluding the first element.
   * If the argument is a pair (cons cell), `cdr` retrieves the second element of that pair.

The terms "car" and "cdr" come from the early days of Lisp and are derived from the original names of the hardware registers on the IBM 704 computer used to implement Lisp. The term "car" stands for "Contents of Address Register," which refers to the first part of a cons cell, and "cdr" stands for "Contents of Decrement Register," referring to the second part of a cons cell.
These functions provide a way to destructure lists and extract individual elements or sublists. They are often used in combination to access specific elements within nested lists or to perform list processing operations. For example:
;; Extracting elements from a list
(car '(1 2 3)) ; returns 1
(cdr '(1 2 3)) ; returns (2 3)

;; Extracting elements from a pair (cons cell)
(car '(1 . 2)) ; returns 1
(cdr '(1 . 2)) ; returns 2

;; Nested list access
(car (cdr '(1 (2 3) 4))) ; returns (2 3)
(cadr '(1 (2 3) 4))      ; equivalent to the previous line, returns (2 3)​

In Lisp, it is common to use shorthand notations for combining `car` and `cdr` operations. For example, `(cadr x)` is equivalent to `(car (cdr x))`, and `(cddr x)` is equivalent to `(cdr (cdr x))`. These shorthand notations provide a more compact and expressive way to work with lists and nested structures.
Advertisement