问题
have got a problem with do this kind of code , can't figure how to search for a element (a) and replace i by ( b) , how to do it? Thx in advance
回答1:
Try this function:
(define subst
(lambda (new old l)
(cond
((null? l) (quote ()))
((atom? (car l))
(cond
((eq? (car l) old) (cons new
(subst new old (cdr l))))
(else (cons (car l)
(subst new old (cdr l))))))
(else (cons (subst new old (car l))
(subst new old (cdr l)))))))
This will search through a list of S expressions and substitute every occurrence of old with an occurrence of new.
回答2:
Start with a list. If it's empty, leave it. If the first element is a list, then you want to call your function recursively. If the first element is equal to what your searching for, cons the replacement onto a recursive call of your function on the rest of the list- you need to keep searching. If none of the earlier conditions are true, cons the first element on to a recursive call of your function for the rest of the list.
(define (find-replace a b list)
(cond
((null? list) '())
((list? (car list)) (cons (find-replace a b (car list)) (find-replace a b (cdr list))))
((eq? (car list) a) (cons b (find-replace a b (cdr list))))
(else
(cons (car list) (find-replace a b (cdr list))))))
来源:https://stackoverflow.com/questions/4542386/searching-and-replacing-n-element-on-list-scheme