我想知道如何用另一个符号替换列表中的符号。这是我想出的,
;; 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替换为'
但是如何在else递归过程中替换' a?
答案 0 :(得分: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)