FirstN / LastN
The FirstN function obtains the first n items from a list. It uses the LastN function in its definition, thus both need to be loaded for FirstN to work.
The LastN function is derived from the Common Lisp Last function. It's renamed to not interfere with the built-in Last function, which obtains only the single last element in the list.
Code
This uses the NthCDR function in its definition, thus both need to be loaded for it to work. Note also the firstN function simply makes use of the lastN - thus both need to be loaded in order for firstN to work.
(defun firstN (lst n / l)
(reverse (lastN (reverse lst) n)))
(defun lastN (lst n /)
(nthcdr (- (length lst) (cond (n) (1))) lst))
Or if you don't want to include NthCDR. The firstN would be the same as above.
(defun lastN (lst n / )
(repeat (- (length lst) n) (setq lst (cdr lst))))
An optimized [1] version for long lists - not needing NthCDR.
(defun LastN (lst n / )
(setq n (- (length lst) n))
(repeat (/ n 4) (setq lst (cddddr lst)))
(repeat (rem n 4) (setq lst (cdr lst)))
lst)
Bibliography
1. Derived from code posted by Elpanov Evgeniy here: http://www.theswamp.org/index.php?topic=32428.msg380205#msg380205
page revision: 8, last edited: 25 Jul 2013 19:51