# weima learns to program

my attempt to do the exercises in sicp.

## Thursday, July 17, 2008

### sicp exercise 2.39

; Exercise 2.39.   Complete the following definitions of reverse (exercise 2.18) in terms of fold-right and fold-left from exercise 2.38:

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

(define (fold-right op initial sequence)
(define (iter result rest)
(if (null? rest)
result
(iter (op (car rest) result)
(cdr rest))))
(iter initial sequence))

(define (fold-left op initial sequence)
(define (iter result rest)
(if (null? rest)
result
(iter (op result (car rest))
(cdr rest))))
(iter initial sequence))

(define (reverse1 seq)
(define (iter result rest)
(cond ((null? rest) result)
(else (iter (cons (car rest) result) (cdr rest)))))
(iter (list) seq))

(define (reverse2 seq)
(fold-right (lambda (x y) (cons x y))  (list) seq))

(define (reverse3 seq)
(fold-left  (lambda (x y) (cons y x))  (list) seq))

(display (reverse1 (list 1 2 3 4)))(newline)
(display (reverse2 (list 1 2 3 4)))(newline)
(display (reverse3 (list 1 2 3 4)))(newline)