Next: , Previous: cons, Up: car cdr & cons

7.3 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 cdring 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 cdrs, the text following the ‘’ shows what is returned.

     (cdr '(pine fir oak maple))
          ⇒(fir oak maple)
     
     (cdr '(fir oak maple))
          ⇒ (oak maple)
     
     (cdr '(oak maple))
          ⇒(maple)
     
     (cdr '(maple))
          ⇒ nil
     
     (cdr 'nil)
          ⇒ nil
     
     (cdr ())
          ⇒ nil

You can also do several cdrs without printing the values in between, like this:

     (cdr (cdr '(pine fir oak maple)))
          ⇒ (oak maple)

In this example, 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 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))
          ⇒ (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))
          ⇒ (pine fir oak maple)
     
     ;; Return a copy without the first element.
     (nthcdr 1 '(pine fir oak maple))
          ⇒ (fir oak maple)
     
     ;; Return a copy of the list without three elements.
     (nthcdr 3 '(pine fir oak maple))
          ⇒ (maple)
     
     ;; Return a copy lacking all four elements.
     (nthcdr 4 '(pine fir oak maple))
          ⇒ nil
     
     ;; Return a copy lacking all elements.
     (nthcdr 5 '(pine fir oak maple))
          ⇒ nil