【问题标题】:How to replace an item by another in a list in DrScheme when given paramters are two items and a list?当给定参数是两个项目和一个列表时,如何在 DrScheme 的列表中用另一个项目替换一个项目?
【发布时间】:2011-01-21 16:35:40
【问题描述】:

当给定的参数是两个项目和一个列表时,如何在 DrScheme 的列表中用另一个项目替换一个项目?

【问题讨论】:

    标签: scheme racket


    【解决方案1】:

    将map 与一个函数一起使用,该函数在其参数等于您要替换的项目时返回替换项目,否则返回参数。

    【讨论】:

      【解决方案2】:
      ; replace first occurrence of b with a in list ls, q? is used for comparison
      (define (replace q? a b ls)
        (cond ((null? ls) '()) 
          ((q? (car ls) b) (cons a (cdr ls)))
          (else (cons (car ls) (replace a b (cdr ls))))))
      

      【讨论】:

        【解决方案3】:
        ; replace first occurrence of b with a in list ls, q? is used for comparison
        (define (replace q? a b ls)
          (cond ((null? ls) '()) 
                ((q? (car ls) b) (replace q? a b (cons a (cdr ls))))
                (else (cons (car ls) (replace a b (cdr ls))))))
        

        【讨论】:

          【解决方案4】:

          这会将列表 lst 中所有出现的 fsym 替换为 DrRacket 中的符号 tsym

          (define (subst fsym tsym lst)
          
          (cond
          
          [(null? lst) lst]
          
          [eq? (first lst) fsym)(cons tsym (subst fsym tsym (rest lst)))]
          
          [else (cons (first lst)(subst fsym tsym (rest lst)))]))
          
          (subst 'a 'b '(f g a h a))
          
          ;the results will be as follows.
          
          '(f g b h b)
          

          【讨论】:

            猜你喜欢
            • 2022-07-18
            • 2015-06-04
            • 1970-01-01
            • 2019-12-24
            • 2017-09-28
            • 2016-08-02
            • 2014-02-11
            • 2021-11-23
            • 2014-07-21
            相关资源
            最近更新 更多