简体   繁体   English

简化表达式F#

[英]Simplify expression F#

I want the expression (xx) to be simplified to 0. 我希望将表达式(xx)简化为0。

type aexpr = 
| CstI of int
| Var of string
| Add of aexpr * aexpr
| Sub of aexpr * aexpr
| Mul of aexpr * aexpr;;

let rec simplify expr =
match expr with
| Add(CstI(n1), CstI(n2)) ->CstI(n1 + n2)
| Sub(CstI(n1), CstI(n2)) ->CstI(n1 - n2)
| Mul(CstI(n1), CstI(n2)) ->CstI(n1 * n2)
| Add(e, CstI(0)) -> simplify e
| Add(CstI(0), e) -> simplify e
| Sub(CstI(0), e) -> simplify e
| Sub(e, CstI(0)) -> simplify e
| Sub(Var(x1), Var(x2)) when x1.Equals(x2) -> CstI(0) // <- not working
| Mul(CstI(0), e) -> CstI(0)
| Mul(e, CstI(0)) -> CstI(0)
| Mul(CstI(1), e) -> simplify e
| Mul(e, CstI(1)) -> simplify e
| _ -> expr;;

This does not do it. 这不会这样做。 I do not see what I am doing wrong. 我看不到我在做什么错。 Hope you can help me :) 希望你能帮我 :)

Edit: It compiles fine but it does not do anything. 编辑:它可以编译,但它不会执行任何操作。 Ie. IE浏览器。

let e = Mul(CstI(1), Add(CstI(4), Sub(Var("x"), Var("x"))));;

In f# interactive: 在f#交互式中:

let result = simplify e;;
val result : aexpr = Add (CstI 4,Sub (Var "x",Var "x"))

Result should be CstI 4 结果应为CstI 4

simplify (Sub (Var "x", Var "x")) works just fine. simplify (Sub (Var "x", Var "x"))工作正常。 The reason that your example does not work is that simplify does not traverse the whole tree, so the Sub (Var "x", Var "x") part of the tree is never simplified. 您的示例不起作用的原因是, simplify不会遍历整个树,因此树的Sub (Var "x", Var "x")部分永远不会得到简化。

In short, you're missing a case Sub (e,e) -> Sub (simplify e, simplify e) and the same for the other operators. 简而言之,您缺少Sub (e,e) -> Sub (simplify e, simplify e)的情况,其他运算符也是如此。

It seems to work here. 它似乎在这里工作。 You're not dealing with a case-sensitivity issue with the string comparison, are you? 您没有通过字符串比较处理区分大小写的问题,对吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM