方案/球拍 - 未定义的功能;初始化前不能使用 [英] Scheme/Racket - Undefined Function; Cannot use before initialization

查看:55
本文介绍了方案/球拍 - 未定义的功能;初始化前不能使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前正在学习 SICP,在第一章接近尾声时,他们要求你为 pi 编程一个值,用pi/4 = (2 * 4 * 4 * 6 * 6 * 8 * ...)/(3 * 3 * 5 * 5 * 7 * 7 *..)

Currently going through SICP, and near the end of the first chapter, they ask you to program a value for pi, with pi/4 = (2 * 4 * 4 * 6 * 6 * 8 * ...) / (3 * 3 * 5 * 5 * 7 * 7 *..)

我定义了以下函数:

;Term and Next are both functions, a and b are the range of the product
(define (product term a next b) 
  (if (> a b) 1
      (* (term a) (product term (next a) next b))))

(define (pi-approx n)
  (define (square x) (* x x))

  (define (num-prod ind) (* (* 2 ind) (* 2 (+ ind 1)))) ; calculates the product in the numerator for a certain term
  (define (denom-prod ind) (square (+ (* ind 2 ) 1))) ;Denominator product at index ind

  (define num (product num-prod 1 inc n))
  (define denom (product denom-prod 1 inc n))

  (* 4 (/ num denom))) ;;Resulting value

当我在 DrRacket 中运行此代码时,出现以下错误:num-prod:未定义;不能在初始化之前使用,即使我在使用之前初始化了几行 num-prod.

When I run this code in DrRacket, I get the following error: num-prod: Undefined; Cannot use before initialization, even though I initialize num-prod a couple of lines before I use it.

我在语法上做错了什么?

What am I doing wrong syntactically?

推荐答案

这是该问题在 Google 上的热门搜索结果之一,所以我想我会添加更多细节:

This is one of the top Google results for the question, so I thought I'd add some more detail:

在大多数 Scheme 实现(例如 R5RS)中,无法保证您的定义的解析顺序.换句话说,它们不是按顺序解析的.是的,您在几行之前定义了 num-prod,但完全有可能先编译 num,因此出现错误.

In most Scheme implementations (such as R5RS), there is no guarantee of the order in which your definitions are parsed. In other words, they are not parsed sequentially. Yes, you defined num-prod a few lines before, but it's entirely possible that num is compiled first, hence the error.

在 Racket 中,lambda 被编译为 letrec* 操作符而不是 letrec,这意味着 保证了顺序解析.这就是为什么改变语言会有所帮助.

In Racket, lambdas are compiled to letrec* operators instead of letrec, meaning that there is a guarantee of sequential parsing. That's why changing languages helped.

这篇关于方案/球拍 - 未定义的功能;初始化前不能使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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