mini-mini-compiler
源代码来自:http://www.cs.nott.ac.uk/~gmh/compiler.lhs
> data Expr = Val Int | Add Expr Expr
>
> eval :: Expr -> Int
> eval (Val n) = n
> eval (Add x y) = eval x + eval y
>
> type Stack = [Int]
>
> type Code = [Op]
>
> data Op = PUSH Int | ADD
>
> exec :: Code -> Stack -> Stack
> exec [] s = s
> exec (PUSH n : c) s = exec c (n:s)
> exec (ADD : c) (m:n:s) = exec c (n+m:s)
>
> comp' :: Expr -> Code -> Code
> comp' (Val n) c = PUSH n : c
> comp' (Add x y) c = comp' x (comp' y (ADD : c))
>
> comp :: Expr -> Code
> comp e = comp' e []
它只支持整型和求和,表达式转换成指令的列表后在堆栈上执行,结果放在栈顶。假设expr为 Add (Val 1) (Val 2),则 comp expr 会得到 [PUSH 1,PUSH 2,ADD],把这个结果丢给exec 则得到[3]。
*Main> let e = Add (Val 1) (Val 2)
*Main> exec (comp e) []
[3]
区区23行代码,代码之美,莫过于此!
标签: haskell
0 Comments:
发表评论
<< Home