【问题标题】:A function in Scheme to replace all occurrences of an element in a list with another elementScheme中的一个函数,用于用另一个元素替换列表中所有出现的元素
【发布时间】:2010-12-27 22:05:13
【问题描述】:

我可以从列表中删除元素,但我不知道如何在 Scheme 中编写一个函数来用另一个元素替换列表中所有出现的元素。 任何帮助将不胜感激。

【问题讨论】:

标签: scheme racket


【解决方案1】:

一个简单的版本可能是这样设计的:

(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可用。
  • 很公平,这可能是真的。
猜你喜欢
  • 2021-11-21
  • 2016-02-09
  • 2021-09-21
  • 2021-01-06
  • 2022-10-20
  • 2021-06-18
  • 2017-07-05
  • 2021-05-19
  • 2015-08-17
相关资源
最近更新 更多