乐正

Actions speak louder than words.

Sicp-ex2-21

问题

过程square-list以一个数值表为参数,返回每个数的平方构成的表:

1
2
(square-list (list 1 2 3 4))
(1 4 9 16)

下面是square-list的两个定义,请填充其中缺少的表达式以完成它们:

1
2
3
4
5
6
7
(define (square-list items)
  (if (null? items)
      nil
      (cons <??> <??>)))

(define (square-list items)
  (map <??> <??>))

解答

练习2.21 (ex2-21.scm) download
1
2
3
4
5
6
7
8
9
10
11
12
13
;; Happy hacking Yuez - Emacs ♥ you!

;; 定义1
(define (square-list items)
  (if (null? items)
      (list)
      (cons (square (car items)) (square-list (cdr items)))))

;; 定义2
(define (square-list items)
  (map (lambda (x)
         (square x))
       items))

测试

1
2
3
4
5
6
7
;; 加载定义1
(square-list (list 1 2 3 4))
;Value 14: (1 4 9 16)

;; 加载定义2
(square-list (list 1 2 3 4))
;Value 15: (1 4 9 16)

draft

« sicp-ex2-20 sicp-ex2-22 »

Comments