Searching and replacing n element on list - scheme

坚强是说给别人听的谎言 提交于 2019-12-02 05:38:25

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.

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))))))
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!