CS_61A_lab10_about_scheme
Write sub-all, which takes a list s, a list of old words, and a list of new words; the last two lists must be the same length. It returns a list with the elements of s, but with each word that occurs in the second argument replaced by the corresponding word of the third argument. You may use substitute in your solution. Assume that olds and news have no elements in common.
eg:
(sub-all '(go ((bears))) '(go bears) '(big game))
(big ((game)))
(define (substitute s old new) (cond ((null? s) nil) ((pair? s) (cons (substitute (car s) old new) (substitute (cdr s) old new))) ((equal? old s) new) (else s) ) ) ;很聪明,就是把所有的问题转化为对第一个的处理,也就是最基础的情况,而上面的pair就是处理是list的情况
;先将list中第一个old全部替换,再替换剩下的元素 (define (sub-all a olds news) (if (null? olds) a (sub-all (substitute a (car olds) (car news)) (cdr olds) (cdr news))))
而我的代码一坨狗屎:
(define (substitute s old new) (if (null? s) nil (if (pair? (car s)) (cons (substitute (car s) old new) (substitute (cdr s) old new)) (if (list? (car s)) (if (equal? (list old) (car s)) (cons (list new) (substitute (cdr s) old new)) (cons (list (car s)) (substitute (cdr s) old new)) ) (if (equal? old (car s)) (cons new (substitute (cdr s) old new)) (cons (car s) (substitute (cdr s) old new)) ) ) ) ) )
重点在于,我没有认识到 [pair? ] and [list?]其实起到了相同的作用 ,都是判断是否存在括号。
在 Scheme 中,pair 和 list 都是数据类型,用于组合多个值以形成复合数据结构。然而,它们有一些区别,包括以下几点:
-
pair表示任何有两个元素的序列。通常,第一个元素是该对的“car”(参考自cons单元),第二个元素是该对的“cdr”(参考自cons单元)。例如,
(cons 1 2)创建了一个新的 pair,它的 car 是 1,cdr 是 2。(cons 'a 'b)创建了一个新的 pair,它的 car 是 'a,cdr 是 'b。 -
list是一种特殊类型的 pair 序列,其中最后一个 pair 的 cdr 是空列表()例如,
(list 1 2 3)创建了一个新的 list,包含元素 1、2 和 3。(list 'a 'b)创建了一个新的 list,包含元素 'a 和 'b。(cons 1 (cons 2 (cons 3 '())))也是一个 list,它包含元素 1、2 和 3。 -
pair和list在其长度和结构上有所不同。pair可以包含任何两个元素,而list仅包含零个或多个元素,并且最后一个元素的cdr始终是空列表()。
总的来说,pair 通常用于表示数据结构中的节点,例如二叉树和图等,而 list 通常用于表示有序的数据集合。在 Scheme 中,pair 和 list 通常可以相互转换,因为任何一个合法的 list 都是一个由 pair 组成的链表,而任何一个合法的 pair 序列都可以被视为一个 list。

浙公网安备 33010602011771号