当给定的参数是两个项目和一个列表时,如何在DrScheme的列表中用另一个项目替换项目?如何在DrScheme的列表中用另一个项目替换项目,当给定的参数是两个项目和一个列表?
1
A
回答
5
使用map
带有一个函数,该函数在参数等于要替换的项目时返回替换项目,否则返回参数。
0
; 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))))))
0
; 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))))))
0
这取代fsym的所有出现在列表中LST到符号TSYM在DrRacket
(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)