乐正

Actions speak louder than words.

Sicp-ex2-39

问题

基于练习2.38的fold-rightfold-left完成reverse(练习2.18)下面的定义:

1
2
3
4
5
(define (reverse sequence)
  (fold-right (lambda (x y) <??>) nil sequence))

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

解答

练习2.39 (ex2-39.scm) download
1
2
3
4
5
6
7
;; Happy hacking, Yuez - Emacs ♥ you!

(define (reverse sequence)
  (accumulate (lambda (x y) (append y (list x))) '() sequence))

(define (reverse sequence)
  (fold-left (lambda (x y) (append (list y) x)) '() sequence))

测试

1
2
3
4
5
6
7
;; 第一个reverse
(reverse (list 1 2 3))
;Value 16: (3 2 1)

;; 第二个reverse
(reverse (list 1 2 3))
;Value 18: (3 2 1)

draft

« sicp-ex2-38 sicp-ex2-40 »

Comments