# Issue: LAST-N (Version 1)

• To: CL-Cleanup@SAIL.Stanford.EDU
• Subject: Issue: LAST-N (Version 1)
• From: Kent M Pitman <KMP@STONY-BROOK.SCRC.Symbolics.COM>
• Date: Fri, 4 Dec 87 16:49 EST
• Cc: KMP@STONY-BROOK.SCRC.Symbolics.COM

```Issue:        LAST-N
References:   LAST (p267)
Category:     ENHANCEMENT
Edit history: 04-Dec-87, Version 1 by Pitman
Status:	      For Internal Discussion

Problem Description:

People always ask why LAST returns a cons and not an element.

BUTLAST takes an argument N but LAST does not.

Proposal (LAST-N:ALLOW-OPTIONAL-ARGUMENT):

Allow LAST to take an optional argument N, saying how many cells to return.

It is an error if N is negative or L is circular.

If N is equal to the number of cons cells in the list L, then the atom which
terminates the list L is returned.

If N is greater than the number of cons cells in the list L, then it is an
error if the list is not a proper list. If in this case the list is a proper
list, then L is returned.

Test Cases:

(LAST    '(A B C) 0) => ()
(BUTLAST '(A B C) 0) => (A B C)

(LAST    '(A B C) 1) => (C)
(BUTLAST '(A B C) 1) => (A B)

(LAST    '(A B C) 2) => (B C)
(BUTLAST '(A B C) 2) => (A)

(LAST    '(A B C) 3) => (A B C)
(BUTLAST '(A B C) 3) => ()

(LAST    '(A B C) 4) => (A B C)
(BUTLAST '(A B C) 4) => ()

(LAST    '(A B C))   => (C)
(BUTLAST '(A B C))   => (A B)

(LAST '(A . B) 0)    => B
(LAST '(A . B) 1)    => (A . B)
(LAST '(A . B) 2)    is an error.

Rationale:

BUTLAST and LAST would select complementary parts of a list in general.
That is (EQUAL L (APPEND (BUTLAST L N) (LAST L N))) would be T for N >= 0
and L being a proper list.

This would make it more obvious why LAST should return a list and not
an element. ie, it would return the "last N elements" where N=1 by default.

Current Practice:

Probably nobody does this.

Very slight. The following code would suffice:

(DEFUN LAST (LIST &OPTIONAL (N 1))
(CHECK-TYPE N (INTEGER 0))
(DO ((L LIST (CDR L))
(R LIST)
(I 0 (+ I 1)))
((ATOM L) R)
(IF (>= I N) (POP R))))

Some implementations might want to provide compiler optimizations for
the N=1 case.

Benefits:

This utility is probably needed often enough to warrant its inclusion.
It's present (as a separate function called NLEFT) in Symbolics Common
Lisp and Interlisp.

Conversion Cost:

None. This is an upward compatible extension.

Aesthetics:

This would make things a little prettier.

Discussion:

This suggestion came up recently on a Symbolics design discussion list.
Symbolics is contemplating offering it as an extension, but it seemed like
the rest of the CL community might want to adopt it, too.  Pitman thinks
it's a nice idea.

```