我正在学习“编程语言:应用程序和解释”,在执行#lang plai之后,我可以在DrRacket 5.2.1中运行前两章的示例。但是当我输入第三章的第一个例子时,如下所示:
(with (x 5) (+ x x))我得到了以下错误:
reference to an identifier before its definition: with我在这本书中没有找到with的定义。我需要图书馆吗?
发布于 2012-07-10 20:04:53
with结构不是在您自己的程序中使用的东西,而是存在于您定义的语言中的东西。换句话说,它是你实现的东西,而不是你使用的东西。请注意,书中总是将其与花括号{with {x ...} ...}一起使用,这是为了避免您遇到的这种混淆--在您实现的语言中的代码中始终使用花括号,圆括号用于您自己的实现代码。
请注意,在球拍中定义自己的with很简单,但这将是错误的,并且可能会让您更加困惑。与其尝试在球拍中使用它,不如照本宣科,在第3章结束时,您将拥有一个适用于WAE语言的解释器--然后您将能够使用它来运行使用with的WAE程序。
顺便说一下,如果您正在寻找一种类似于with的球拍形式,那么请查看let --惟一的区别是let允许您指定多个绑定,而不是只指定一个绑定。
发布于 2013-03-13 06:00:59
(with (x a) <body>) is just a synonym for ((lambda x <body>) a)如果你仍然有这个问题,你可以使用
((lambda x (+ x x)) 5)发布于 2012-07-13 12:02:50
很抱歉,我昨天没能测试这些例子!看起来还是有错误,我在第三章的末尾输入了以下代码:
(define (parse sexp)
(cond
[(number? sexp) (num sexp)]
[(list? sexp)
(case (first sexp)
[(+) (add (parse (second sexp))
(parse (third sexp)))]
[(-) (sub (parse (second sexp))
(parse (third sexp)))])]))
(define-type WAE
[num (n number?)]
[add (lhs WAE?)(rhs WAE?)]
[sub (lhs WAE?) (rhs WAE?)]
[with (name symbol?) (named-expr WAE?)(body WAE?)]
[id (name symbol?)])
(define (subst expr sub-id val)
(type-case WAE expr
[num (n) expr]
[add (l r) (add (subst l sub-id val)
(subst r sub-id val))]
[sub (l r) (sub (subst l sub-id val)
(subst r sub-id val))]
[with (bound-id named-expr bound-body)
(if (symbol=? bound-id sub-id)
(with bound-id
(subst named-expr sub-id val)
bound-body)
(with bound-id
(subst named-expr sub-id val)
(subst bound-body sub-id val)))]
[id (v) (if (symbol=? v sub-id) val expr)]))
(define (calc expr)
(type-case WAE expr
[num (n) n]
[add (l r) (+ (calc l) (calc r))]
[sub (l r) (- (calc l) (calc r))]
[with (bound-id named-expr bound-body)
(calc (subst bound-body
bound-id
(num (calc named-expr))))]
[id (v) (error 'calc "free identifier")]))然后,我测试“with”,如下21页所示
(calc (parse '{with {x {+ 55}} {+ x x}}))
我得到了错误:
"type-case: expected a value from type WAE, got: #"原因是需要一个更新的解析,我从谷歌得到了一些关于第三章的片段,例如,在CS 345 Progamming Languages中,它的解析定义如下:
(define parse
(lambda (sexp)
(cond
[(number? sexp) (num sexp)]
[(symbol? sexp) (id sexp)]
[(list? sexp)
(case (first sexp)
[(+)(add (parse (second sexp))
(parse (third sexp)))]
[(-) (sub (parse (second sexp))
(parse (third sexp)))]
[(with) (with (first (second sexp))
(parse (second (second sexp)))
(parse (third sexp)))]
)])))最后,我得到了一个正确的结果:
(calc (parse '{with {x {+ 55}} {+ x x}}) ) => 20
https://stackoverflow.com/questions/11412546
复制相似问题