私は「プログラミング言語: アプリケーションと解釈」を勉強しており、実行後に DrRacket 5.2.1 で最初の 2 つの章の例を実行でき#lang plai
ます。しかし、第3章の最初の例を次のように入力したとき:
(with (x 5) (+ x x))
次のエラーが発生しました。
reference to an identifier before its definition: with
with
この本には の定義が見つかりませんでした。図書館は必要ですか?
構成は、with
独自のプログラムで使用するものではなく、代わりに定義する言語で存在するものです。言い換えれば、それはあなたが使用するものではなく、あなたが実装するものです。本は常に中括弧でそれを使用していることに注意してください、そしてそれはあなたが持っているこの正確な混乱を避けることを目的としています-中括弧は常にあなたが実装する言語のコードで使用され、丸括弧はあなた自身のために使用されます実装のコード。{with {x ...} ...}
Racketで独自に定義するのwith
は簡単ですが、それは間違いであり、混乱を招く可能性があることに注意してください。Racketで使用する代わりに、この本に従う必要があります。第3章の終わりに、WAE言語の通訳が機能します。これを使用して、WAEプログラムを実行できるようになります。を使用しますwith
。
with
ちなみに、に似たラケットフォームを探している場合は、調べてください。let
唯一の違いは、let
1つだけではなく複数のバインディングを指定できることです。
(with (x a) <body>) is just a synonym for ((lambda x <body>) a)
それでも問題が解決しない場合は、次を使用してこれを解決できます。
((lambda x (+ x x)) 5)
昨日これらの例をテストできなかったのはとても残念です! まだエラーがあるようですが、第 3 章の最後のコードを次のように入力しました。
(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")]))
そして、以下の 21 ページのように「with」をテストします
(calc (parse '{with {x {+ 5 5}} {+ xx}}))
エラーが発生しました:
"type-case: expected a value from type WAE, got: #"
この理由は、更新された解析が必要であるためです。たとえば、CS 345 Progamming Languagesでは、第 3 章について Google からいくつかのスニペットを取得しました。その解析の定義は次のとおりです。
(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 {+ 5 5}} {+ xx}}) ) => 20