2017-04-13 65 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,這意味着順序解析的保證。這就是改變語言的原因。