灯下 登录
计算机科学 / SICP / 2.2.1 Representing Sequences

Exercise 2.23 · 习题

Exercise 2.23: The procedure for-each is
similar to map. It takes as arguments a procedure and a list of
elements. However, rather than forming a list of the results, for-each
just applies the procedure to each of the elements in turn, from left to right.
The values returned by applying the procedure to the elements are not used at
all—for-each is used with procedures that perform an action, such as
printing. For example,

(for-each
(lambda (x) (newline) (display x))
(list 57 321 88))

57
321
88

The value returned by the call to for-each (not illustrated above) can

be something arbitrary, such as true. Give an implementation of

for-each.

练习 2.23:过程 for-each 与 map 类似,它以一个过程和一个元素的表作为参数。但与 map 不同的是,for-each 不构造结果的表,而只是依次从左到右将该过程应用于每个元素。应用过程于元素所返回的值完全不被使用——for-each 用于那些执行某些动作的过程,例如打印。例如,

(for-each
(lambda (x) (newline) (display x))
(list 57 321 88))

57
321
88

调用 for-each 的返回值(上面未展示)可以是某个任意值,例如 true。请给出 for-each 的一个实现。

Racket #lang sicp
(for-each
 (lambda (x) (newline) (display x))
 (list 57 321 88))

57
321
88