SICP 习题 (2.20)解题总结: 不确定数量参数

来源:互联网 发布:苹果官方同步软件 编辑:程序博客网 时间:2024/05/21 06:28

SICP 习题 2.20 引入了一种新的函数调用方式,就是带 . 符号的不确定参数调用方式。


题中也讲到了, Scheme支持这种调用方式,如果我们把方法定义成下面这个样子


(define (my-method first-p  .  others-p)  ;…..)


我们就可以在调用方法my-method时传入大于2的任何数量的参数,比如:

(my-method 1 2 3 4 5 6)

这时my-method获得两个变量,first-p是1,而others-p是一个list,成员有2 3 4 5 6,就是说others-p等于(2 3 4 5 6)


题目要求我们实现一个叫same-parity的方法,该方法接受不确定数量的参数,返回和第一个参数具有同样奇偶性的所有参数。


这道题不难,题目的意思主要是介绍这种不确定数量参数的使用方式。


方法定义如下:


(define (same-parity first . others)  (display first)  (newline)  (display others)  (newline)  (if (not (null? others))      (if (odd? first)  (cons first (filter odd? others))  (cons first (remove odd? others)))      (list first)))

这里有点偷懒,使用了系统的filter过程和remove过程, 系统的filter过程可以返回一个列表中满足条件的成员,而系统过程remove返回所有不满足条件的成员。

而odd?过程也是一个系统过程,用于判断一个数的奇偶性。

不过方法里面加了两行打印代码,用于打印first参数和others参数,这样在测试的时候可以更清楚地观察两个参数的值。



0 0