Searching and replacing n element on list - scheme

匆匆过客 提交于 2019-12-02 06:40:30

问题


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

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