gpt4 book ai didi

Trouble implementing streams with Racket(使用球拍实现流时出现问题)

转载 作者:bug小助手 更新时间:2023-10-24 22:40:07 24 4
gpt4 key购买 nike



I am working my way through the Wizard Book Structure and Interpretation of Programming in my free evenings. All was going well, until I tried to implement streams in Chapter Three. I am using (Dr)Racket, not Scheme, so this might be my problem.

在我空闲的晚上,我正在努力学习向导书的结构和编程的解释。在我尝试在第三章实现Streams之前,一切都很顺利。我用的是(DR)球拍,而不是方案,所以这可能是我的问题。


The crux of the problem is that when I try to create streams I get a memory issue: "interactions disabled; out of memory". This suggests to me that there is something wrong with the way I am using delay.

问题的症结在于,当我尝试创建流时,我得到了一个内存问题:“交互被禁用;内存不足”。在我看来,这表明我使用延迟的方式有问题。


Thanks in advance for any advice :)

提前感谢您的任何建议:)


I have tried the code suggested in the text:

我已经尝试了文本中建议的代码:


#lang racket

(define (cons-stream a b)
(cons a (delay b)))

(define (car-stream s)
(car s))

(define (cdr-stream s)
(force (cdr s)))

where I am calling Racket's delay and force. I have also tried implementing delay and force myself following the text, but I come across the same memory error.

我把球拍的延迟和武力称为。我也尝试了实现延迟和强制自己遵循文本,但我遇到了相同的记忆错误。


To test that this is all working I tried writing an infinite stream of 1s:

为了测试这一切是否正常工作,我尝试编写一个无限的1流:


(define (ones) (cons-stream 1 (ones)))

and a very large interval:

和一个非常大的间隔:


(define (interval low high)
(if (> low high)
null
(cons-stream low
(interval (+ low 1) high))))

(define (first-integers n)
(interval 0 n))

(define test-interval
(first-integers 10000000000000000000000000))

To my understanding of the text, neither of these should cause problems because we only generate the streams when required. However, something I've done causes a memory issue and so I think the code tries to generate the entire stream!

根据我对文本的理解,这两种方法都不会造成问题,因为我们只在需要时才生成流。然而,我所做的一些事情导致了内存问题,所以我认为代码会尝试生成整个流!


更多回答

Tip: Install the sicp package and use #lang sicp instead of #lang racket when working through the exercises in the book

提示:安装SiCp包,在练习本书中的练习时使用#lang SiCp而不是#lang球拍

cons-stream needs to be implemented as a macro, not a function, iirc.

Cons-stream需要实现为宏,而不是函数iirc。

See for example stackoverflow.com/questions/14640833/…

例如,参见Stackoverflow.com/Questions/14640833/…

@Shawn thanks for the tips and link :) What does iirc mean?

@Shawn感谢你的提示和链接:)iirc是什么意思?

If I Recall Correctly

如果我没记错的话

优秀答案推荐

We can not define

我们不能定义


(define (cons-stream a b)
(cons a (delay b)))

because define creates a function cons-stream, so on every function call all arguments will be evaluated before the call is made. Which defeats the whole purpose -- b will be already evaluated.

因为定义创建了一个函数cons-stream,所以在每次调用函数时,都会在调用之前计算所有参数。这与整个目的背道而驰--b将被评估。


See also How is delay implemented?.

另见延迟是如何实现的?


更多回答

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com