stream - 没有元素的无限流

标签 stream scheme lisp racket infinite

我们刚刚在我的一门编程类(class)中学习了流。我已经完成了这几周分配的任务,除了这个:定义一个没有元素的无限流。我已经浏览了 SICP 书的第 3.5 章,但我仍然不明白诀窍是什么。一些提示会很棒 ^^

最佳答案

答案取决于您使用的确切流类型。

基本上有两种不同类型的流:

- empty streams
- streams consisting of an element followed by an stream

因此您需要两种不同类型的值来表示这两种类型。

在 SICP ( ) 中,他们写道:

There is a distinguishable object, the-empty-stream, which cannot be the result of any cons-stream operation, and which can be identified with the predicate stream-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/

相关文章:

c++ 模板类无法修复 ostream 和 istream 函数

Java 8 : Get files from folder/subfolder

c# - 防止多次处理对象

clojure - 在 clojure 中实现方案样式宏

data-structures - 将函数应用于 Racket 中的树结构

c++ - 交错的 cout 和 cin 操作是否需要显式刷新?

scheme - 将代码从 Lisp 转换为 SCHEME

recursion - 将递归函数定义为迭代?

string - 从 lisp 中的八位字节解码单个字符

lisp - 使用 asdf3 在 slime 中编译 defsystem 时出现无效的相对路径名错误