球拍中的流 [英] streams in racket

查看:32
本文介绍了球拍中的流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能帮助我更好地理解如何编写流?

Can anyone help me better understand how to write a stream?

我知道流是一个无限的值序列,我学习编程它们的方式是将它们表示为一个 thunk,当被调用时会产生一对 (1) 序列中的第一个元素和 (2) athunk 表示第二个到无穷大元素的流

I understand that a stream is an infinite sequence of values and the way I have learned programming them is a representing them as a thunk that when called produces a pair of (1) the first element in the sequence and (2) a thunk that represents the stream for the second-through-infinity elements

例如:

(define powers-of-two
    (letrec ([f (lambda (x) (cons x (lambda () (f (* x 2)))))])
        (lambda () (f 2))))

我在这里理解它只是产生 2 的幂并且访问这些例如调用 (car (powers-of-two)) 将导致 2并调用 (car ((cdr (powers-of-two)))) 将导致 4

I understand here that it is just producing a powers of two and to access these for example calling (car (powers-of-two)) would result in 2 and calling (car ((cdr (powers-of-two)))) would result in 4

现在我正在尝试编写一个名为 red-blue 的流,它在字符串 redblue 之间交替,但我有点困惑如何构建它

Now I am trying to write a stream called red-blue that alternates between strings red and blue but I am a little confused about how to construct it

推荐答案

为了大致了解 Scheme 中的流,我推荐部分 §3.5 Streams.它将教您解决与流相关的问题(例如问题中的问题)的基本概念.

For a general understanding of streams in Scheme, I'd recommend section §3.5 Streams in the SICP book. It'll teach you the basic concepts to solve stream-related problems such as the one in the question.

关于问题中的问题,这里是解决它的总体思路:

Regarding the problem in the question, here's the general idea to solve it:

  • 构建两个无限流,一个只产生字符串"red",另一个"blue"
  • 合并两个流,从一个元素中获取一个元素,然后从另一个元素中获取一个元素(交替),此过程在 SICP 中称为 interleave

这篇关于球拍中的流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆