sicp每日一题[2.33]

37 篇文章 0 订阅
23 篇文章 0 订阅

Exercise 2.33

Fill in the missing expressions to complete the following definitions of some basic list-manipulation operations as accumulations:

; p 表示一个函数,sequence 表示一个列表
; 这个函数将对列表中每一个元素进行 p 操作
(define (map p sequence)
  (accumulate (lambda (x y) <??>) nil sequence))

(define (append seq1 seq2)
  (accumulate cons <??> <??>))

(define (length sequence)
  (accumulate <??> 0 sequence))

这道题还是有一定难度的,尤其是第一个 (map p sequence),我开始没明白它的意思,不知道 lambda 两个参数要干嘛,所以先做的后面2个,做到第三个的时候才发现是 accumulate 函数中 op 函数需要2个参数,明白了这一点,剩下的就比较好处理了,x 就表示当前要处理的项,y 就是原函数中的递归项。

(define (map p sequence)
  (accumulate
   (lambda (x y) (if (null? x) y (cons (p x) y)))
   nil
   sequence))

(define (append seq1 seq2)
  (accumulate cons seq2 seq1))

(define (length sequence)
  (accumulate
   (lambda (x y) (if (null? x) y (+ y 1)))
   0
   sequence))


(define odds (list 1 3 5 7 9))
(define evens (list 2 4 6 8 10))

(map square odds)
(map sqrt evens)
(append odds evens)
(length odds)

; 执行结果
'(1 9 25 49 81)
'(1.4142156862745097 2.0000000929222947 2.4494897427875517 2.8284271250498643 3.162277665175675)
'(1 3 5 7 9 2 4 6 8 10)
5
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值