gpt4 book ai didi

scheme - Scheme中循环定义的问题

转载 作者:行者123 更新时间:2023-12-04 06:53:12 25 4
gpt4 key购买 nike

我目前正在使用 Guile 作为练习的主要语言来完成 SICP。在执行第 3.5 章中的练习时,我发现了一个奇怪的行为。我已经在各种平台上使用 Guile 1.4、Guile 1.8.6 和 Guile 1.8.7 重现了这种行为,并且确定它不是特定于我的设置。

此代码工作正常(并计算 e):

  (define y (integral (delay dy) 1 0.001))
(define dy (stream-map (lambda (x) x) y))
(stream-ref y 1000)

以下代码应该给出相同的结果:
  (define (solve f y0 dt)
(define y (integral (delay dy) y0 dt))
(define dy (stream-map f y))
y)
(stream-ref (solve (lambda (x) x) 1 0.001) 1000)

但它会产生错误消息:
standard input:7:14: While evaluating arguments to stream-map in expression (stream-map f y):
standard input:7:14: Unbound variable:
y ABORT: (unbound-variable)

因此,当嵌入到过程定义中时, (define y ...) 不起作用,而在 REPL 的全局环境中的过程之外,它工作正常。

我在这里做错了什么?如有必要,我也可以发布辅助代码(即积分、流映射等的定义)。除了 cons-stream 的系统相关代码之外,它们都在书中。我自己对 Guile 的 cons-stream 实现如下:
(define-macro (cons-stream a b)
`(cons ,a (delay ,b)))

最佳答案

当您在 REPL 中逐一评估定义与将它们放入 solve 时发生的主要区别是在第一种情况下,它们按顺序计算,因此 y表达式 (stream-map <some-function> y)指的是已经在范围内,而具有内部定义或 letrec ,尚不可用。

好笑的是,我在做 SICP 的时候用的 MIT Scheme,当时没有这个问题,现在还在处理 letrec和内部定义不同:

;; this is an error
(letrec ((xs '(1 2 3)) (ys (map (lambda (x) (+ x 1)) xs))) ys)

;; this is still an error (and is treated as such by Guile),
;; yet evaluates to (2 3 4) in MIT Scheme
(let () (define xs '(1 2 3)) (define ys (map (lambda (x) (+ x 1)) xs)) ys)

我不确定原始的“算法语言方案修订报告”或 R2RS,但至少来自 R3RS 的内部定义应该等同于 letrec .显然,麻省理工学院环境的这种特殊性影响了这本书……或者相反。

关于scheme - Scheme中循环定义的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2828996/

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