下面的简化函数试图简化类型
((2 + 3) * (2 + 4))
的数学表达式来
(2 * (3 + 4))
。如何使用有源图案来实现的数学表达式简化
理想情况下,我想写出匹配表达式为:
| Product (Sum (c, a), Sum (c, b)) -> Product (c, Sum (a, b))
但是,这给我的“C在这种模式势必两次”错误。所以我诉诸守卫条件。
我想知道是否有更好的方法来使用主动模式来实现这一点?
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)
您拥有它的方式是正确的,没有简短的符号。 –
你如何“简化”(2 + 3)*(2 + 4)'等于'30'到'2 *(3 + 4)'等于'14'?这些东西并不等同。 – TheInnerLight
[“Expert F#4.0”](http://www.worldcat.org/oclc/936182944)有关于[简化代数表达式]的章节(https://books.google.com/books?id=XKhPCwAAQBAJ&pg=PA339&lpg = PA339&DQ =专家+ F%23 + 4.0 +简化+代数+表达。&源= BL&OTS = GHXjjeHPbV&SIG = I4wbdiF6WVWOx4EdES6KS4ohh7M&HL = EN&SA = X&VED = 0ahUKEwio54a0jKHSAhXC1CYKHQemCd4Q6AEIITAB#v = onepage&q =专家%20F%23%204.0%20Simplifying%20Algebraic%20Expressions。&F = false)这可能有帮助。 –