SICP 习题2.61~2.62 排序表示的adjoin和union-set函数

adjoin函数要注意的是怎样把x插入当前的序列,union-set的写法可以参考书上给出的intersection-set。
my.scm文件将给出一些所有代码经常会用到的逻辑。譬如这次的先换行后打印

my.scm

(define (out x)
  (newline)
  (display x))

2.62.scm

(load "my.scm")

(define (element-of-set? x set)
  (cond ((null? set) #f)
        ((= x (car set)) #t)
        ((< x (car set)) #f)
        (else element-of-set? x (cdr set))))

(define (adjoin-set x set)
  (cond ((null? set) x)
        ((< x (car set)) (cons x set))
        ((= x (car set)) set)
        (else 
          (cons (car set) (adjoin-set x (cdr set))))))

(define set1 '(1 2 3 5 6))
(out (adjoin-set 1 set1))
(out (adjoin-set 4 set1))
(out (adjoin-set 7 set1))

(define (union-set set1 set2)
  (cond ((null? set1) set2)
        ((null? set2) set1)
        (else 
          (let ((x1 (car set1)) (x2 (car set2)))
            (cond ((= x1 x2) (cons x1 (union-set (cdr set1) (cdr set2)))) ((< x1 x2) (cons x1 (union-set (cdr set1) set2))) ((> x1 x2) (cons x2 (union-set set1 (cdr set2)))))))))

(define set2 '(5 6 7 8 9))
(out (union-set set1 set2))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值