Subject: bug#7174: 23.2; `last' can be made faster by using `length'

From: Glenn Morris <[email-masked]>
Date: Wed, 13 Oct 2010 18:48:56 -0400

Juanma Barranquero wrote:

> They are not equivalent:
>
> (last '(1 . 2) 0)  => 2
> (last-new '(1 . 2) 0) => nil

See also http://debbugs.gnu.org/cgi/bugreport.cgi?bug=7206

(defun last-new2 (list &optional n)
  "Return the last link of LIST.  Its car is the last element.
If LIST is nil, return nil.
If N is non-nil, return the Nth-to-last link of LIST.
If N is bigger than the length of LIST, return LIST."
  (if n
      (and (>= n 0)
         (let ((m (safe-length list)))
              (if (< n m) (nthcdr (- m n) list) list)))
    (and list
     (nthcdr (1- (safe-length list)) list))))

(last-new2 '(1 . 2) 0) => 2