2014-11-02 96 views
0

我在想如何用另一個符號替換列表中的符號。這是我想出的,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 
     [(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' 一)

很好,看起來像我的代碼只有擺脫他們而不是相互替換它們。任何建議這裏出了什麼問題?

我在想,也許,

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

應改寫爲

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

這有助於 '一個帶' D

但如何 '與d' 一個在更換更換其他遞歸過程?

回答

1

那麼你很接近,但你忘了cons如果您發現s1

(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) 
+0

!噢,那是正確的!謝謝 – ads27 2014-11-02 21:27:56

+0

不客氣;-) – uselpa 2014-11-02 21:33:24