sicp cons-stream是如何实现的?

时间:2013-02-01 06:18:33

标签: scheme sicp

我正在处理scip的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))))

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

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

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

我猜测延迟功能不起作用,但我不知道如何修复它。我在Mac上运行麻省理工学院计划。

更新1

所以现在将cons-stream作为宏,可以定义整数。

但后来又出现了另一个错误。

(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

2 个答案:

答案 0 :(得分:5)

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

试试这个(未经测试):

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

P.S。出于类似的原因,您的delay也需要是一个宏。然后,在您修复delay后,您可以直接使用cons-stream delay

答案 1 :(得分:1)

你不能将延迟定义为一个函数,因为在调用它之前,Scheme会评估它的参数 - 这正是你试图推迟的。 SICP明确表示延迟应该是一种特殊形式。

相关问题