2017-04-13 64 views
0

目前通过SICP去之前不能使用,并且靠近第一章结束时,他们问你能编写圆周率的值,与 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: Undefined; Cannot use before initialization,即使我在在我使用它之前,itialize num-prod几行。

我在做什么语法错误?

+0

一旦我添加了'(define inc add1)',我就很好地工作了。你正在使用REPL还是定义区域? –

+0

我不确定两者之间有什么区别,但我使用编辑器的顶部......下面是它的样子:[link](https://imgur.com/a/m2R0A )。注意,我确实有'(define(inc x)(+ x 1))'代码,所以我相当确定这不是问题的一部分。 –

+0

小突破!我问了一些问题,并解决了这个问题是使用'#lang racket'而不是'#lang sicp' ......我不太确定为什么这会改变任何事情,但任何见解都会受到欢迎! –

回答

2

这是顶级谷歌结果的问题之一,所以我想我会添加一些更详细:

在大多数Scheme实现(如R5RS),没有秩序的保证,其中你的定义被解析。换句话说,它们不会被顺序分析。是的,您在前几行定义了num-prod,但完全有可能首先编译num,因此是错误。

球拍,lambda表达式被编译成letrec*运营商,而不是letrec,这意味着顺序解析的保证。这就是改变语言的原因。