用符号表达式替换符号 [英] Replacing a symbol in a symbolic expression

查看:149
本文介绍了用符号表达式替换符号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望替换成对中第一次出现的符号。例如:
take

 (define n'((a。b)。(a。d))) 

我定义了一个方法上下文用'()替换X的第一个实例(最左边的)
替换a应该给我:

$ p $ ((()。b)a。d)

然而我被卡住了,因为我的方法取代了所有的实例,我不确定如何为此添加一个检查。
我的代码如下:

$ $ p $ $ $ $ $ $ $ (s(s))
(if(equal?s sym)'()s))
(else(cons(context(car s)sym)
(context(cdr s)sym))))

()。b)()。d)

有帮助吗?谢谢

解决方案

最快捷的方法是使用一个标志来指示替换是否已经完成,

 (define(context sxp sym)
(define done #f)
(let loop( ((sxp))
(cond(done sxp)
((pair?sxp)(cons(loop(car sxp))(loop(cdr sxp))))
((eq? (sxp))))

使用 set!并不是很优雅,但另一种方法是让该过程返回2个值,并且生成的 let-值代码在可读性IMO方面会更差。

另外请注意,我没有使用 atom? 因为它没有在标准Scheme中定义;通常的方法是先后测试 null?然后 pair?,并处理<$ c $中的原子大小写c> else 子句。


I wish to replace the first occurrence of a symbol within pairs. For example: take

(define n '((a . b) . (a . d)))

and i define a method context to replace the first instance (left most) of X with '() replacing a should give me:

((() . b) a . d)

however i am stuck as my method replaces ALL instances and i am not sure how to add a check for this. my code is as follows:

(define (context s sym)
  (cond ((null? s) #f)
        ((atom? s)
         (if (equal? s sym) '() s ))
        (else (cons (context (car s) sym)
                    (context (cdr s) sym)))))

which gives : ((() . b) () . d)

any help? Thank you

解决方案

The quickest way is to use a flag indicating whether the replacement has already been done, something along the lines of:

(define (context sxp sym)
  (define done #f)
  (let loop ((sxp sxp))
    (cond (done sxp)
          ((pair? sxp) (cons (loop (car sxp)) (loop (cdr sxp))))
          ((eq? sym sxp) (set! done #t) '())
          (else sxp))))

It's not very elegant to use set!, but the alternative would be to have the procedure return 2 values, and the resulting let-values code would be even worse in terms of readability IMO.

Also note that I didn't use atom? because it's not defined in standard Scheme; the usual way is to successively test null? then pair?, and handle the atom case in the else clause.

这篇关于用符号表达式替换符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆