【发布时间】:2016-02-24 20:38:53
【问题描述】:
我有一个 SML 程序,它表示一种语言,其表达式由值组成:
datatype Value = IntVal of int
| ListVal of Value list
datatype Exp = Const of Value
| Plus of Exp * Exp
| Minus of Exp * Exp
| Times of Exp * Exp
我还在编写一个将表达式转换为值的 eval 函数。如果表达式是 Plus 表达式(例如 Plus (Const (IntVal 1), Const (IntVal 1)) 代表 1+1),我只想取出存储在 IntVal 中的整数并将它们加在一起并返回。
但据我所知,我必须有一个看似多余的 case 语句,只有一个 case 才能获得 IntVal 数据类型中的整数:
(*Evaluates an Exp and returns a Value*)
fun eval e =
(*Evaluate different types of Exp*)
case e of
(*If it's a constant, then just return the Value*)
Const v => v
(*If it's a Plus, we want to add together the two Values*)
| Plus (x,y) =>
(*Case statement with only one case that seems redundant*)
case (eval x, eval y) of
(IntVal xVal, IntVal yVal) => IntVal (xVal + yVal)
有没有简单的方法来简化这个?我想做这样的事情,这当然不是有效的 SML:
fun eval e =
case e of
Const v => v
| Plus (x,y) => IntVal (eval x + eval x)
【问题讨论】:
-
这对我来说真的没有意义。你的
Value数据类型是递归的——它本质上是一种对应于树的类型,其中节点可以有任意数量的子节点,叶子是整数。将两棵这样的树相加或相乘是什么意思? -
我意识到 Value + Value 没有意义,所以我想要一种将这些值转换/处理为 IntVals 的方法,而不需要 case 语句。对我来说,对于单一类型的案例来说,案例陈述似乎太大而沉重
-
@JohnColeman:在为编程语言定义抽象语法时,这种树很常见。你最终得到了一个可以表达无意义事物的类型,一个生成这些无意义树的解析器,最后你在类型检查器中解决了这些无意义的问题。对于决定一段抽象语法是否无意义的语言是一个更复杂的过程,将这个决定放在一个单独的类型检查步骤中被证明是一个有用的结构。
标签: functional-programming sml ml