【发布时间】:2011-01-21 16:35:40
【问题描述】:
当给定的参数是两个项目和一个列表时,如何在 DrScheme 的列表中用另一个项目替换一个项目?
【问题讨论】:
当给定的参数是两个项目和一个列表时,如何在 DrScheme 的列表中用另一个项目替换一个项目?
【问题讨论】:
将map 与一个函数一起使用,该函数在其参数等于您要替换的项目时返回替换项目,否则返回参数。
【讨论】:
; replace first occurrence of b with a in list ls, q? is used for comparison
(define (replace q? a b ls)
(cond ((null? ls) '())
((q? (car ls) b) (cons a (cdr ls)))
(else (cons (car ls) (replace a b (cdr ls))))))
【讨论】:
; replace first occurrence of b with a in list ls, q? is used for comparison
(define (replace q? a b ls)
(cond ((null? ls) '())
((q? (car ls) b) (replace q? a b (cons a (cdr ls))))
(else (cons (car ls) (replace a b (cdr ls))))))
【讨论】:
这会将列表 lst 中所有出现的 fsym 替换为 DrRacket 中的符号 tsym
(define (subst fsym tsym lst)
(cond
[(null? lst) lst]
[eq? (first lst) fsym)(cons tsym (subst fsym tsym (rest lst)))]
[else (cons (first lst)(subst fsym tsym (rest lst)))]))
(subst 'a 'b '(f g a h a))
;the results will be as follows.
'(f g b h b)
【讨论】: