sicp cons-stream 是如何实施的? [英] how is the sicp cons-stream implemented?

查看:35
本文介绍了sicp cons-stream 是如何实施的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究 scip 的流部分,但对如何定义流感到困惑.

I'm working through the streams section of the scip and am stuck on how to define a stream.

以下是我的代码:

(define (memo-func function)
  (let ((already-run? false)
        (result false))
    (lambda ()
      (if (not already-run?)
          (begin (set! result (function))
                 (set! already-run? true)
                 result)
          result))))


(define (delay exp)
  (memo-func (lambda () exp)))

(define (force function)
  (function))

(define the-empty-stream '())
(define (stream-null? stream) (null? stream))
(define (stream-car stream) (car stream))
(define (stream-cdr stream) (force (cdr stream)))

(define (cons-stream a b) (cons a (memo-func (lambda () b))))

如果我按照书中描述的方式定义整数:

If I define integers the way that the book descibes:

(define (integers-starting-from n)
   (cons-stream n (integers-starting-from (+ n 1))))
(define integers (integers-starting-from 1))

我收到一条消息:正在中止!:超出了最大递归深度.

I get a message saying: Aborting!: maximum recursion depth exceeded.

我猜 delay 功能不起作用,但我不知道如何修复它.我正在我的 Mac 上运行 MIT 方案.

I'm guessing that the delay function is not working but I don't know how to fix it. I am running the MIT scheme on my Mac.

所以现在使用 cons-stream 作为宏,可以定义整数.

So now with cons-stream as a macro, the integers can be defined.

但后来我又犯了一个错误.

But then I've got another error.

(define (stream-take n s)
  (cond ((or (stream-null? s)
             (= n 0)) the-empty-stream)
        (else (cons-stream (stream-car s)
                           (stream-take (- n 1) (stream-cdr s))))))

(stream-take 10 integers)
;ERROR - Variable reference to a syntactic keyword: cons-stream

更新 2

请忽略上面的更新 1

推荐答案

cons-stream 需要是一个宏才能让您的示例代码正常工作.否则,cons-stream 的调用将急切地评估其所有参数.

cons-stream needs to be a macro in order for your sample code to work correctly. Otherwise the invocation of cons-stream will evaluate all its arguments eagerly.

试试这个(未测试):

(define-syntax cons-stream
  (syntax-rules ()
    ((cons-stream a b)
     (cons a (memo-func (lambda () b))))))

附言出于类似的原因,您的 delay 也需要是一个宏.那么在你修复delay之后,你就可以让你的cons-stream直接使用delay.

P.S. Your delay needs to be a macro also, for similar reasons. Then after you fix delay, you can make your cons-stream use delay directly.

这篇关于sicp cons-stream 是如何实施的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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