【发布时间】:2010-12-28 12:46:50
【问题描述】:
假设我正在为 F# 中的特定领域语言构建解析器。
我已经定义了一个有区别的联合来表示表达式:
type Expression =
| Equality of Expression*Expression
| NonEquality of Expression*Expression
| Or of Expression*Expression
| And of Expression*Expression
| If of Expression*Expression
| IfElse of Expression*Expression*Expression
| Bool of bool
| Variable of string
| StringLiteral of string
现在,我已经建立了一个 Expression 类型的 AST,并希望为它生成代码。
我有一个函数可以对表达式进行类型推断和类型检查。
定义如下
let rec InferType expr =
match expr with
| Equality(e1,e2) -> CheckTypes (InferType e1) (InferType e2)
| Or(e1,e2) -> CheckTypes (InferType e1) (InferType e2)
| And(e1,e2) -> CheckTypes (InferType e1) (InferType e2)
...
我还有另一个函数来生成遵循类似模式的代码:获取一个表达式,为联合中的每个项目编写模式匹配语句。
我的问题是:这是在 F# 中的惯用方式吗?
在我看来,如果工会的每个成员都用它在本地定义自己的InferType 和GenerateCode,那会更干净。
如果我使用 C#,我将定义一些名为 Expression 的抽象基类,并为 InferType 和 GenerateCode 定义虚拟方法,然后在每个子类中覆盖它们。
还有其他方法吗?
【问题讨论】:
标签: f#