【发布时间】: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