【问题标题】:scheme replace a symbol in a list with another symbol方案用另一个符号替换列表中的符号
【发布时间】:2014-11-03 05:24:40
【问题描述】:

我想知道如何用另一个符号替换列表中的符号。这是我想出的,

;; swap:  s1 s2 los -> los 
;; given a list of symbols and symbol1 symbol2 
;; return a list with all occurrences of s1 replaced with 
;; s2 and all occurrences of s2 replaced with s1

(define (swap s1 s2 1st)
   (cond 
      [(empty? 1st) empty]
      [(cons? 1st)
          (cond
              [(symbol=? (first 1st) s1) (swap s2 s1 (rest 1st))]
              [else (cons (first 1st)
                    (swap  s1 s2 (rest 1st)))])]))

测试;

(swap 'a 'd (list 'a 'b 'c 'd))=> list ('d 'b 'c 'a)

好吧,看起来我的代码只是摆脱了它们而不是相互替换它们。有什么建议吗?

我在想也许,

[(symbol=? (first 1st) s1) (swap s2 s1 (rest 1st))] 

应该改写成

[(symbol=? (first 1st) s1) (cons s2 (rest 1st))]  

这有助于将 'a 替换为 'd

但是如何在 else 递归过程中将 'd 替换为 'a 呢?

【问题讨论】:

    标签: scheme


    【解决方案1】:

    嗯,你很接近,但如果你找到s1,你忘了cons

    (define (swap s1 s2 1st)
      (cond 
        [(empty? 1st) empty]
        [(cons? 1st)
         (cond
           [(symbol=? (first 1st) s1) (cons s2 (swap s2 s1 (rest 1st)))] ; <--- cons added
           [else (cons (first 1st)
                       (swap s1 s2 (rest 1st)))])]))
    

    测试:

    > (swap 'a 'd (list 'a 'b 'c 'd))
    '(d b c a)
    

    【讨论】:

      猜你喜欢
      • 2016-03-08
      • 1970-01-01
      • 2022-11-29
      • 1970-01-01
      • 2015-01-28
      • 2022-07-23
      • 2011-01-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多