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

From Drewiki
Jump to: navigation, search

Contents

Problem

Complete the following definitions of reverse (see SICP exercise 2.18) in terms of fold-right and fold-left from SICP exercise 2.38:

(define (reverse sequence)
   (fold-right (lambda (x y) <??>) nil sequence))
 
(define (reverse sequence)
   (fold-left (lambda (x y) <??>) nil sequence))

Solution 1

(define (reverse sequence)
  (fold-right (lambda (x y)
                (append y (list x)))
              nil
              sequence))

Tests

(reverse (list 1 2 3))

Output:

(3 2 1)


Solution 2

(define (reverse sequence)
  (fold-left (lambda (x y)
               (cons y x))
             nil
             sequence))

Tests

(reverse (list 1 2 3))

Output:

(3 2 1)
Personal tools