当给定的参数是两个项目和一个列表时,如何在DrScheme的列表中替换另一个项目?

时间:2011-01-21 16:35:40

标签: scheme racket

如果给定的参数是两个项目和列表,如何在DrScheme的列表中替换另一个项目?

4 个答案:

答案 0 :(得分:5)

map与一个函数一起使用,该函数在其参数等于您要替换的项时返回替换项,否则返回参数。

答案 1 :(得分: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))))))

答案 2 :(得分: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))))))

答案 3 :(得分:0)

这会将列表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)