问题
I am trying to solve an arithmetic expression in prolog (implementation - eclipse prolog). The arithmetic expression to be solved is like this:
A * (C + B * X) + D * X = E
X is the value to be computed, and all others (A,B,C,D,E) are all numbers.
For example: 5 * (3 + 2*X) + 2*X = 39, on computing should assign X with the value 2.
The query(goal) that would be entered into Prolog would take the form:
?- compute( 5*(3+2*X)+2*X = 39, Result).
The 'Result' and value of 'X' should be tied (assigned) together. How do I write the prolog program to do this..?
Thank You.
回答1:
I assume that you use fd
, not ic
. It simplifies things a bit.
:-lib(fd).
Further assuming that you only have equations and not inequalities, and only one variable X, then you can do it in two steps:
compute(L=R, X) :-
term_variables(L, [X]),
L #= R.
First, extract the variable from the left hand side, then post a constraint that computes the equation. If the equation is valid, this will instantiate your variable.
Edit
With the ic
library, use eval(L)#=R
.
来源:https://stackoverflow.com/questions/9209058/how-to-do-arithmetic-expression-evaluation-in-prolog