我想问一下如何简化表达式,例如:
I wanted to ask how I can simplify expressions like:
1+2+a*5+0/b-c*0 = 3+a*5特别是我如何在列表中分隔这些表达式.
And especially how can I separate such expressions in lists.
推荐答案使用统一可以简化 Prolog 中的表达式,但这有时会导致意想不到的结果.在这个例子中,当匹配"一个表达式时,表达式中的两个不同变量是统一的.一种模式,即使它们的目的是不同的:
It's possible to simplify expressions in Prolog using unification, but this sometimes leads to unexpected results. In this example, two different variables in an expression are unified when "matching" a pattern, even if they were intended to be distinct:
:- initialization(main). simplify(A+A,2*A). main :- simplify(A+B,C), writeln(C).在这种情况下,simplify(A+B,C) 会将 A 与 B 统一起来.
In this case, simplify(A+B,C) would unify A with B.
为了解决这个问题,我使用subsumes_term/2 匹配模式而不统一表达式中的变量.subsumes_term(A+A,Input) 将不匹配 A+B 除非 A 已经与 B 统一:
To solve this problem, I use subsumes_term/2 to match a pattern without unifying the variables in an expression. subsumes_term(A+A,Input) will not match A+B unless A is already unified with B:
simplify(Input,2*A) :- subsumes_term(A+A,Input).这个 subsumes_term/2 谓词通常对元编程很有用:我用它写了一个 Prolog-to-Minizinc 编译器.
This subsumes_term/2 predicate is often useful for metaprogramming: I used it to write a Prolog-to-Minizinc compiler.
更多推荐
简化 Prolog 中的表达式
发布评论