【发布时间】:2018-09-08 18:15:42
【问题描述】:
我试图用 lst 替换每第 n 次出现的 old 和 new 作为一个列表,可以是原子列表或列表列表。当 lst 是列表列表时,我无法将第 n 个 old 替换为 new。
(define (replace lst n old new)
(cond ((null? lst) '())
((and (= n 1) (eq? (car lst) old)) (cons new (cdr lst)))
((not (atom? (car lst)))
(cons (replace (car lst) n old new) (replace (cdr lst) n old new)))
((and (atom? (car lst)) (eq? (car lst) old)) (cons old (replace (cdr lst) (- n 1) old new)))
(else (cons (car lst) (replace (cdr lst) n old new)))))
调用上面的函数
(replace '(a b c a d e f g a t y a g) '3 'a 'o)
给我(a b c a d e f g o t y a g),但是当我输入列表列表时,我无法获得正确的输出
(replace '((a a) b c a d e f g a t y a g) '3 'a 'o)
这可能是因为当我的函数进入列表 (a) 时,我递减的 n 计数器没有返回。有没有办法通过n计数器?
【问题讨论】: