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.18

From Drewiki
Jump to: navigation, search

Problem

Define a procedure reverse that takes a list as argument and returns a list of the same elements in reverse order:

(reverse (list 1 4 9 16 25))

Output:

(25 16 9 4 1)


Solution

There are several ways to implement this procedure, but the easiest way is to use append. Note that the result of appending a list foo to the empty list is just the list foo.

(define nil (quote ()))
 
(define (reverse items)
  (if (null? items)
      nil
      (append (reverse (cdr items)) (cons (car items) nil))))

Test:

(reverse (list 1 4 9 16 25))

Output:

(25 16 9 4 1)
Personal tools