3

我在运行 SICP(计算机程序的结构和解释)第 3.5.4 节(流和延迟评估)中的示例代码时遇到问题;SICP 部分可以在这里找到:http: //mitpress.mit.edu/sicp/full-text/book/book-ZH-24.html#%_sec_3.5.4

我正在使用 DrRacket 版本 5.2.1,使用 Neil Van Dyke ( SICP PLaneT 1.17 ) 的 SICP 支持语言设置,可以在此处找到:http: //www.neilvandyke.org/racket-sicp/#%28part ._安装%29

下面显示的代码使用了流。如上所述设置环境后,DrRacket 已经提供了cons-stream程序和forcedelay但是不可用stream-carstream-cdr所以,我必须定义它们。在下面的代码中,我还定义了一些通用流函数:stream-mapstream-ref和。add-streamsscale-stream

我试图使工作的整个代码如下。solve它包括使用积分程序 ( )对一阶微分方程进行数值求解的程序 ( integral),该程序使用延迟参数 ( delayed-integrand);这些程序来自第 3.5.4 节。

(define (stream-car stream) (car stream))
(define (stream-cdr stream) (force (cdr stream)))
(define (stream-map proc . argstreams)
  (if (stream-null? (car argstreams))
      the-empty-stream
      (cons-stream
       (apply proc (map stream-car argstreams))
       (apply stream-map
              (cons proc (map stream-cdr argstreams))))))
(define (stream-ref s n)
  (if (= n 0)
      (stream-car s)
      (stream-ref (stream-cdr s) (- n 1))))

(define (add-streams s1 s2)
  (stream-map + s1 s2))

(define (scale-stream stream factor)
  (stream-map (lambda (x) (* x factor)) stream))

(define (integral delayed-integrand initial-value dt)
  (define int
    (cons-stream initial-value
                 (let ((integrand (force delayed-integrand)))
                   (add-streams (scale-stream integrand dt)
                                int))))
  int)

(define (solve f y0 dt)
  (define y (integral (delay dy) y0 dt))
  (define dy (stream-map f y))
  y)

当我将上面的定义放入 DrRacket 并单击运行时,不会出现错误。但是,当我尝试在交互窗口中执行以下行时,会发生错误:

(stream-ref (solve (lambda (y) y) 1 0.001) 1000)

错误信息是:

mcar: expects argument of type <mutable-pair>; given #<undefined>

出现此错误时,DrRacket 会高亮显示程序定义的主体stream-car,如下图所示:

DrRacket 错误


是什么导致了这个错误?我已经在前面的示例(stream-carstream-cdrstream-map和)中使用了上面的流过程add-streams并且scale-stream它们有效。integral当我在程序之外使用它时,该程序也有效solve;例如,如果我定义(define ones (cons-stream 1 ones))然后我定义(define s (integral (delay ones) 1 1))然后我执行(stream-ref s 1000),它会正确地给出输出1001

4

1 回答 1

5

您报告的错误很奇怪,我看不到在哪里mcar使用 - 或可变状态。试试这个设置,它适用于我,无需使用 Neil Van Dyke 的支持语言:

#lang racket

(define the-empty-stream '())

(define (stream-null? stream)
  (null? stream))

(define-syntax cons-stream
  (syntax-rules ()
    ((cons-stream head tail)
     (cons head (delay tail)))))

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

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

; ... the rest is the same as in your question
于 2012-12-22T00:42:40.300 回答