【发布时间】:2010-12-27 22:05:13
【问题描述】:
我可以从列表中删除元素,但我不知道如何在 Scheme 中编写一个函数来用另一个元素替换列表中所有出现的元素。 任何帮助将不胜感激。
【问题讨论】:
我可以从列表中删除元素,但我不知道如何在 Scheme 中编写一个函数来用另一个元素替换列表中所有出现的元素。 任何帮助将不胜感激。
【问题讨论】:
一个简单的版本可能是这样设计的:
(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 来更简洁地执行此操作。
【讨论】:
(define (replace old new list) ...)。至于实际的实现——不要这样做,使用map。
map 相去甚远的指南或教科书。
map可用。