替换(可能是嵌套的)列表中第一次出现的符号 [英] Replace first occurrence of symbol in (possibly nested) list
本文介绍了替换(可能是嵌套的)列表中第一次出现的符号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在可能包含列表的列表中用另一个符号(比如 '+
)替换某个符号的第一次出现(比如 '-
).也就是说,
I would like to replace just the first occurrence of a certain symbol (say '-
) with another symbol (say '+
) inside a list that may contain lists. That is to say,
'(((-)))
会变成 '(((+)))
'((-) - b)
变成 '((+) - b)
推荐答案
这是另一个不同的选项:使用可变状态来找出第一次替换发生的时间:
Here's another, different option: using mutable state to find out when the first replace has happened:
(define (replace-first)
(let ((found #f))
(define (replacer exp old new)
(cond ((null? exp) '())
((not (pair? exp))
(cond ((and (eq? exp old) (not found))
(set! found #t) new)
(else exp)))
(else
(cons (replacer (car exp) old new)
(replacer (cdr exp) old new)))))
replacer))
((replace-first) '(((-))) '- '+)
=> '(((+)))
((replace-first) '((-) - b) '- '+)
=> '((+) - b)
((replace-first) '(+ 1 2) '+ '-)
=> '(- 1 2)
((replace-first) '((+) 1 2) '+ '-)
=> '((-) 1 2)
((replace-first) '(1 2 ((+)) 3 4) '+ '-)
=> '(1 2 ((-)) 3 4)
((replace-first) '() '+ '-)
=> '()
((replace-first) '(1 2 ((((((+ 3 (+ 4 5)))))))) '+ '-)
=> '(1 2 ((((((- 3 (+ 4 5))))))))
这篇关于替换(可能是嵌套的)列表中第一次出现的符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文