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
[(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' 一个在更换更换其他递归过程?
答
那么你很接近,但你忘了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)
!噢,那是正确的!谢谢 – ads27 2014-11-02 21:27:56
不客气;-) – uselpa 2014-11-02 21:33:24