【发布时间】:2017-09-10 05:10:08
【问题描述】:
目前正在通过 SICP,在第一章快要结束时,他们要求您为 pi 编程一个值,使用
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,尽管我在使用之前将 num-prod 初始化了几行。
我在语法上做错了什么?
【问题讨论】:
-
添加
(define inc add1)后对我来说效果很好。您使用的是 REPL 还是定义区域? -
我不太确定两者之间的区别是什么,但我正在使用编辑器的顶部...这是它的样子:link。旁注,我确实有
(define (inc x) (+ x 1))代码,所以我有理由确定这不是问题的一部分。 -
小突破!我四处询问,解决问题的方法是使用
#lang racket而不是#lang sicp...我不确定为什么这会改变任何事情,但欢迎任何见解! -
它可能将所有内部定义归为一个
letrec,从而导致错误。这意味着前 3 个定义是letrec,接下来的两个定义是let。只是永远不要使用内部defines,反正这是一个没有意义的方便语法糖,真正的东西是let/letrec。