乐正

Actions speak louder than words.

Sicp-ex2-23

问题

过程for-eachmap类似,它以一个过程和一个元素表为参数,但它并不返回结果的表, 只是将这一过程从左到右应用于各个元素,将过程应用于元素得到的值都丢掉不用。for-each 通常用于执行了某些动作的过程,如打印等。看下面例子:

1
2
3
4
5
6
(for-each (lambda (x) (newline) (display x))
          (list 57 321 88))

57
321
88

for-each返回的值(上面没有显示)可以是某种任意的东西,例如逻辑值真。请给出一 个for-each的实现。

解答

练习2.23 (ex2-23.scm) download
1
2
3
4
5
6
;; Happy hacking Yuez - Emacs ♥ you!

(define (for-each operator items)
  (cond ((not (null? items))
         (operator (car items))
         (for-each operator (cdr items)))))

测试

1
2
3
4
5
6
7
(for-each (lambda (x) (newline) (display x))
    (list 57 321 88))

57
321
88
;Unspecified return value

draft

« sicp-ex2-22 sicp-ex2-24 »

Comments