我们刚刚在我的一门编程类(class)中学习了流。我已经完成了这几周分配的任务,除了这个:定义一个没有元素的无限流。我已经浏览了 SICP 书的第 3.5 章,但我仍然不明白诀窍是什么。一些提示会很棒 ^^
最佳答案
答案取决于您使用的确切流类型。
基本上有两种不同类型的流:
- empty streams
- streams consisting of an element followed by an stream
因此您需要两种不同类型的值来表示这两种类型。
在 SICP ( sicp ) 中,他们写道:
There is a distinguishable object,
the-empty-stream
, which cannot be the result of anycons-stream
operation, and which can be identified with the predicatestream-null?
在 Scheme 中定义可区分(唯一)对象的一种方法是分配 一个新的 cons cell - 它的地址对于那个 cell 是唯一的。
(define the-empty-stream (list 'this-is-the-empty-stream))
(define (stream-null? x) (eq? x the-empty-stream))
在 Racket 中,我们可以简单地使用一个结构来表示空流
(struct the-empty-stream ())
(define stream-null? the-empty-stream?)
stream->list
等函数需要处理这两种类型的列表。
回到您的问题:如果您使用的是 SICP 流,答案很简单。
表达式 the-empty-stream
将为您提供一个空流。
如果您要定义自己的,则需要选择一种表示方式 一个空流 - 然后仔细修改所有流函数 也必须处理空流。
关于stream - 没有元素的无限流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50187676/