乐正

Actions speak louder than words.

Sicp-ex2-18

问题

请定义出过程reverse,它以一个表为参数,返回的表中所包含的元素与参数表相同,但 排列顺序与参数表相反:

1
2
3
(reverse (list 1 4 9 16 25))

(25 16 9 4 1)

解答

练习2.18 (ex2-18.scm) download
1
2
3
4
5
6
7
8
9
;; Happy hacking Yuez - Emacs ♥ you!

(define (reverse items)
  (define (reverse-iter remain-items result)
    (if (null? remain-items)
  result
  (reverse-iter (cdr remain-items)
            (cons (car remain-items) result))))
  (reverse-iter items (list)))

测试

1
2
3
4
5
6
7
8
(reverse (list 1 2 3 4))
;Value 21: (4 3 2 1)

(reverse (list 1 4 9 16 25))
;Value 22: (25 16 9 4 1)

(reverse (list))
;Value: ()

draft

« sicp-ex2-11 sicp-ex2-17 »

Comments