Go to the previous, next section.

` nthcdr `

The ` nthcdr `

function is associated with the ` cdr `

function.
What it does is take the ` cdr `

of a list repeatedly.

If you take the ` cdr `

of the list ```
(pine fir
oak maple)
```

, you will be returned the list ` (fir oak maple) `

. If you
repeat this on what was returned, you will be returned the list
` (oak maple) `

. (Of course, repeated ` cdr `

ing on the original
list will just give you the original ` cdr `

since the function does
not change the list. You need to evaluate the ` cdr `

of the
` cdr `

and so on.) If you continue this, eventually you will be
returned an empty list, which in this case, instead of being shown as
` () `

is shown as ` nil `

.

For review, here is a series of repeated ` cdr `

s, the text following
the ``@result{'`} shows what is returned.

(cdr '(pine fir oak maple)) @result{}(fir oak maple) (cdr '(fir oak maple)) @result{} (oak maple) (cdr '(oak maple)) @result{}(maple) (cdr '(maple)) @result{} nil (cdr 'nil) @result{} nil (cdr ()) @result{} nil

You can also do several ` cdr `

s without printing the values in
between, like this:

(cdr (cdr '(pine fir oak maple))) @result{} (oak maple)

In this case, the Lisp interpreter evaluates the innermost list first.
The innermost list is quoted, so it just passes the list as it is to the
innermost ` cdr `

. This ` cdr `

passes a list made up of the
second and subsequent elements of the list to the outermost ` cdr `

,
which produces a list composed of the third and subsequent elements of
the original list. In this example, the ` cdr `

function is repeated
twice and returns a list that consists of the original list without its
first two elements.

The ` nthcdr `

function does the same as repeating the call to
` cdr `

. In the following example, the argument 2 is passed to the
function ` nthcdr `

, along with the list, and the value returned is
the list without its first two items, which is exactly the same
as repeating ` cdr `

twice on the list:

(nthcdr 2 '(pine fir oak maple)) @result{} (oak maple)

Using the original four element list, we can see what happens when
various numeric arguments are passed to ` nthcdr `

, including 0, 1,
and 5:

;; Leave the list as it was. (nthcdr 0 '(pine fir oak maple)) @result{} (pine fir oak maple) ;; Return a copy without the first element. (nthcdr 1 '(pine fir oak maple)) @result{} (fir oak maple) ;; Return a copy of the list without three elements. (nthcdr 3 '(pine fir oak maple)) @result{} (maple) ;; Return a copy lacking all four elements. (nthcdr 4 '(pine fir oak maple)) @result{} nil ;; Return a copy lacking all elements. (nthcdr 5 '(pine fir oak maple)) @result{} nil

It is worth mentioning that ` nthcdr `

, like ` cdr `

, does not
change the original list--the function is non-destructive. This is
in sharp contrast to the ` setcar `

and ` setcdr `

functions.

Go to the previous, next section.