【发布时间】:2017-02-20 23:31:24
【问题描述】:
下面的简化函数试图简化类型的数学表达式((2 + 3) * (2 + 4))
到(2 * (3 + 4)).
理想情况下,我想将匹配表达式写为:
| Product (Sum (c, a), Sum (c, b)) -> Product (c, Sum (a, b))
但这给了我“c 在这种模式下绑定了两次”错误。所以我诉诸守卫条件。
我想知道是否有更好的方法来使用 Active Patterns 来实现这一点?
type Expr =
| Number of int
| Sum of Expr * Expr
| Product of Expr * Expr
let rec eval =
function
| Number n -> n
| Sum (l, r) -> eval l + eval r
| Product (l, r) -> eval l * eval r
let rec show =
function
| Number n -> n.ToString()
| Sum (l, r) -> "(" + show l + " + " + show r + ")"
| Product (l, r) -> "(" + show l + " * " + show r + ")"
let rec simplify =
function
| Product (Sum (c, a), Sum (d, b)) when (c = d) -> Product (c, Sum (a, b))
| Sum (l, r) -> Sum (simplify l, simplify r)
| Product (l, r) -> Product (simplify l, simplify r)
| e -> e
let c = Product (Sum (Number 2, Number 3), Sum (Number 2, Number 4))
show c
eval c
show (simplify c)
【问题讨论】:
-
你的方式是正确的,没有更短的符号。
-
您如何将等于
30的(2 + 3) * (2 + 4)“简化”为等于14的2 * (3 + 4)?这些东西是不等价的。 -
"Expert F# 4.0" 有一个关于 Simplifying Algebraic Expressions 的部分可能会有所帮助。
-
您可以下载"Expert F# 4.0"的源代码
-
@TheInnerLight - 你是对的 :)
标签: f# symbolic-math