sicp每日一题[2.20]

35 篇文章 0 订阅
21 篇文章 0 订阅

Exercise 2.20

The procedures +, *, and list take arbitrary numbers of arguments. One way to define such procedures is to use d e f i n e define define with d o t t e d − t a i l n o t a t i o n dotted-tail notation dottedtailnotation. In a procedure definition, a parameter list that has a dot before the last parameter name indicates that, when the procedure is called, the initial parameters (if any) will have as values the initial arguments, as usual, but the final parameter’s value will be a list of any remaining arguments. For instance, given the definition
(define (f x y . z) ⟨body⟩)
the procedure f can be called with two or more arguments. If we evaluate
(f 1 2 3 4 5 6)
then in the body of f, x will be 1, y will be 2, and z will be the list (3 4 5 6). Given the definition
(define (g . w) ⟨body⟩)
the procedure g can be called with zero or more arguments. If we evaluate
(g 1 2 3 4 5 6)
then in the body of g, w will be the list (1 2 3 4 5 6).
Use this notation to write a procedure s a m e − p a r i t y same-parity sameparity that takes one or more integers and returns a list of all the arguments that have the same even-odd parity as the first argument. For example,

(same-parity 1 2 3 4 5 6 7)
(1 3 5 7)
(same-parity 2 3 4 5 6 7)
(2 4 6)

这道题也是看着唬人,题干挺长,但是主要在介绍如何定义参数个数不定的函数,真正的题目就最后一段,就是要根据第一个参数的奇偶性,把后面参数中跟第一个参数奇偶性相同的找出来。

(define (same-parity x . y)
  (define (iter items r result)
    (cond ((null? items) result)
          ((= r (remainder (car items) 2)) (iter (cdr items) r (cons (car items) result)))
          (else (iter (cdr items) r result))))
  (let ((r (remainder x 2)))
    (reverse (iter y r (cons x nil)))))


(same-parity 1 2 3 4 5 6 7)
(same-parity 2 3 4 5 6 7)
(same-parity 2)

; 执行结果
'(1 3 5 7)
'(2 4 6)
'(2)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值