Replacing a symbol in a symbolic expression

前端 未结 2 406
借酒劲吻你
借酒劲吻你 2020-12-22 09:14

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

2条回答
  •  Happy的楠姐
    2020-12-22 09:40

    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.

提交回复
热议问题