为啥要写post呢?
hlinzhou · 2007-09-01
<< Don Walser
|
首 页
|
blognothing >>
2007-09-01
构造一个可运行的解释器(二):Interpreting Arithmetic
- [
编程
]
版权声明
:转载时请以超链接形式标明文章原始出处和作者信息及
本声明
http://hlinzhou.blogbus.com/logs/8038486.html
note: This series of article follows the PLAI(
Programming Languages: Application and Interpretation
) book
上一节我们实现了一个将Concrete Syntax转化为Abstract Syntax的简单Parser,这一节我们将为这个超级简单的解释器添加求值功能,换句话说,现在我们已经从Syntax晋级Semantics了;-)
这个简单的语言现在只包括数字,加法和减法,而且加法和减法是二元操作符.根据这个语义,我们可以先写出一些Test:
;;tests
(test (calc (parse '3)) 3)
(test (calc (parse '{+ 3 4})) 7)
(test (calc (parse '{+ {- 3 4} 7})) 6)
求值的代码也很简单:
;;calc: AE->number
;;计算AE
(define (calc an-ae)
(type-case AE an-ae
[num (n) n]
[add (l r) (+ (calc l) (calc r))]
[sub (l r ) (- (calc l) (calc r))]))
运行测试:
欢迎使用 DrScheme, 版本 371 [3m].
语言: PLAI.
(list 'good 3 3)
(list 'good 7 7)
(list 'good 6 6)
>
通过~
随机文章:
构造一个可运行的解释器(一):Prelude
2007-08-24
blognothing
2007-09-09
用Dev-C++编译Python扩展
2007-06-14
TiddlyWiki的文件保存功能是如何实现的
2007-06-09
用中文写注释
2007-06-06
收藏到:
Del.icio.us
Tag:
Interpreter
Scheme
引用地址:
hlinzhou
发表于
09:45:19
|
编辑
|
继续话题
|
转发
|
推荐
发表评论
原始快照:web.archive.org