Note: this wiki is now retired and will no longer be updated!

The static final versions of the pages are left as a convenience for readers. Note that meta-pages such as "discussion," "history," etc., will not work.

SICP exercise 2.17

From Drewiki
Jump to: navigation, search

Problem

Define a procedure last-pair that returns the list that contains only the last element of a given (nonempty) list:

(last-pair (list 23 72 149 34))

Output:

(34)


Solution

We need a procedure that cdrs down the list:

(define nil (quote ()))
 
(define (last-pair items)
  (let ((rest (cdr items)))
    (if (null? rest)
        items
        (last-pair rest))))

Note that it's safe to cdr the list before checking that the cdr is empty, because the constraint on the input list is that it's non-empty.

Test:

(last-pair (list 23 72 149 34))

Output:

(34)
Personal tools