我可以从列表中删除元素,但我不知道如何在 Scheme 中编写一个函数来用另一个元素替换列表中所有出现的元素。任何帮助将不胜感激。
问问题
4153 次
1 回答
3
一个简单的版本可能会设计成这样:
(define (replace old-element new-element list)
; if the list is null, just return null
; else if the car of the list is equal to old-element
; run replace on the rest of the list, and cons new-element onto it
; else
; run replace on the rest of the list, and cons the car onto it)
(我把细节留给你,因为你必须边做边学。)
请记住,在 Scheme 中,最自然的做事方式通常是从旧列表中逐个组合一个新列表,而不是尝试一次对旧列表进行微小的更改。
请注意,您也可以map
更简洁地执行此操作。
于 2009-12-18T03:37:11.787 回答