nthcdr
nthcdr Function
Syntax:
nthcdr n list → tail
Arguments and Values:
n—a non-negative integer .
list—a list, which might be a dotted list or a circular list.
tail—an object.
Description:
Returns the tail of list that would be obtained by calling cdr n times in succession.
Examples:
(nthcdr 0 ’()) → NIL
(nthcdr 3 ’()) → NIL
(nthcdr 0 ’(a b c)) → (A B C)
(nthcdr 2 ’(a b c)) → (C)
(nthcdr 4 ’(a b c)) → ()
(nthcdr 1 ’(0 . 1)) → 1
(locally (declare (optimize (safety 3)))
(nthcdr 3 ’(0 . 1)))
Error: Attempted to take CDR of 1.
Exceptional Situations:
Should signal an error of type type-error if n is not a non-negative integer .
For n being an integer greater than 1, the error checking done by (nthcdr n list) is the same as for (nthcdr (- n 1) (cdr list)); see the function cdr.
See Also:
cdr, nth, rest
Expanded Reference: nthcdr
Getting the tail after n cdr operations
nthcdr returns the result of applying cdr n times to a list. It effectively skips the first n elements.
(nthcdr 0 '(a b c d))
=> (A B C D)
(nthcdr 1 '(a b c d))
=> (B C D)
(nthcdr 2 '(a b c d))
=> (C D)
(nthcdr 4 '(a b c d))
=> NIL
nthcdr beyond the end of the list
If n is greater than the length of the list, nthcdr returns NIL.
(nthcdr 10 '(a b c))
=> NIL
(nthcdr 0 nil)
=> NIL
(nthcdr 3 nil)
=> NIL
nthcdr with dotted lists
When applied to a dotted list, nthcdr can return the non-nil terminating atom.
(nthcdr 1 '(a . b))
=> B
(nthcdr 2 '(a b . c))
=> C
Relationship to nth
nth is equivalent to (car (nthcdr n list)).
(let ((lst '(10 20 30 40)))
(values (nth 2 lst)
(car (nthcdr 2 lst))))
=> 30
=> 30
Practical use: dropping elements from a list
nthcdr provides a simple way to skip a fixed number of elements from the front of a list.
(defun drop (n lst)
"Return the list with the first n elements removed."
(nthcdr n lst))
(drop 2 '(a b c d e))
=> (C D E)
(drop 0 '(a b c))
=> (A B C)
(drop 5 '(a b c))
=> NIL