搜索并替换列表中的 n 元素 - 方案

发布于 2024-10-09 08:42:52 字数 52 浏览 0 评论 0原文

在执行此类代码时遇到问题,无法弄清楚如何搜索元素(a)并用(b)替换i,该怎么做?提前谢谢

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

诺曦 2024-10-16 08:42:52

从一个清单开始。如果是空的,就留下它。如果第一个元素是列表,那么您想递归地调用您的函数。如果第一个元素等于您搜索的元素,则将替换替换为对列表其余部分的函数的递归调用 - 您需要继续搜索。如果前面的条件都不成立,则将第一个元素用于对列表其余部分的函数进行递归调用。

(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))))))

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))))))
金兰素衣 2024-10-16 08:42:52

试试这个函数:

(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)))))))

这将搜索 S 表达式列表,并将每次出现的 old 替换为 new 的出现。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文