使用 DrRacket 运行 SICP 第 3.5.4 节中的代码

fav*_*avq 3 scheme sicp racket

我在运行 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

下面显示的代码使用了流。随着环境设置如上,手续cons-streamforcedelay已经可以从DrRacket。但是,stream-carstream-cdr无法获得; 所以,我必须定义它们。在下面的代码,我也定义了一些通用的流函数:stream-mapstream-refadd-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)
Run Code Online (Sandbox Code Playgroud)

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

(stream-ref (solve (lambda (y) y) 1 0.001) 1000)
Run Code Online (Sandbox Code Playgroud)

错误信息是:

mcar: expects argument of type <mutable-pair>; given #<undefined>
Run Code Online (Sandbox Code Playgroud)

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

DrRacket 错误


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

Ósc*_*pez 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
Run Code Online (Sandbox Code Playgroud)