【发布时间】:2015-03-29 14:16:38
【问题描述】:
惯用的 F# 可以很好地表示经典的递归表达式数据结构:
type Expression =
| Number of int
| Add of Expression * Expression
| Multiply of Expression * Expression
| Variable of string
连同其上的递归函数:
let rec simplify_add (exp: Expression): Expression =
match exp with
| Add (x, Number 0) -> x
| Add (Number 0, x) -> x
| _ -> exp
...哎呀,这不像写的那样工作; simplify_add 需要重复出现在子表达式中。在这个很容易做的玩具示例中,只需要几行额外的代码,但在实际程序中会有几十种表达式类型;人们宁愿避免为每个对表达式进行操作的函数添加数十行样板代码。
有没有办法表达“默认情况下,在子表达式上重复”?比如:
let rec simplify_add (exp: Expression): Expression =
match exp with
| Add (x, Number 0) -> x
| Add (Number 0, x) -> x
| _ -> recur simplify_add exp
recur 可能是某种高阶函数,它使用反射来查找类型定义等?
【问题讨论】: