Scheme 方案用另一个符号替换列表中的符号

Scheme 方案用另一个符号替换列表中的符号,scheme,Scheme,我想知道如何用另一个符号替换列表中的符号。这是我想到的 ;; 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

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

;; 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)))])]))
测试

(交换'a'd(列表'a'b'c'd))=>列表('d'b'c'a)

看起来我的代码只是去掉了它们,而不是互相替换。有什么建议吗

我在想也许

[(symbol=? (first 1st) s1) (swap s2 s1 (rest 1st))] 
应该改写为

[(symbol=? (first 1st) s1) (cons s2 (rest 1st))]  
这有助于将“a”替换为“d”


但是如何在else递归过程中用a替换d呢

你很接近,但是如果你发现
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)