2011-01-21 63 views

回答

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)