SICP_2.21-2.23

本文提供了Scheme语言中三种不同实现方式的square-list函数示例代码,包括递归方式、使用map函数以及迭代方式,并展示了如何使用for-each函数来遍历列表。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 1 #lang racket
 2 
 3 ;;;;;;;;;;;;;;;;;;;2.21
 4 (define (square-list items)
 5   (if (null? items)
 6       null
 7       (cons (square (car items))
 8             (square-list (cdr items)))))
 9 
10 (define (square x)
11   (* x x))
12 ;;
13 (define (square-list2 items)
14   (map square items))
15 
16 ;;;;test
17 (square-list (list 1 2 3 4))
18 (square-list2 (list 1 2 3 4))
19 
20 ;;;;;;;;;;;;;;;;;;;;2.22
21 (define (square-list3 items)
22   (define (iter things answer)
23     (if (null? things)
24         answer
25         (iter (cdr things)
26               (append answer
27                       (list (square (car things)))))))
28   (iter items '()))
29 
30 ;;test
31 (square-list3 (list 1 2 3 4))
32 
33 ;;;;;;;;;;;;;;;;;;;;2.23
34 (define (for-each proc items)
35   (cond ((not (null? items))
36          (proc (car items))
37          (for-each proc (cdr items)))))
38 
39 ;;test
40 (for-each (lambda (x) (newline) (display x)) (list 57 321 88))

 

转载于:https://www.cnblogs.com/tclan126/p/6395556.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值