1

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.

false
  • 10,264
  • 13
  • 101
  • 209
kallakafar
  • 725
  • 3
  • 11
  • 27

1 Answers1

4

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.

twinterer
  • 2,416
  • 1
  • 15
  • 13
  • Thanks for the snippet, I tested and it worked. I am however new to prolog and could not understand how X is computing the value. I assume the #= is a delayed constraint. Could you please guide me as to how the solution is being computed? Thank You. – kallakafar Feb 09 '12 at 10:48
  • 1
    Yes, `#=/2` denotes an integer constraint. See section 3.1 in ECLiPSe's Constraint Library Manual, which explains the ic solver. What's happening inside is that the constraint's propagation algorithm gets started when the constraint is posted. This updates the domains of the variables that are attached to the constraint, in order to make them consistent. In this case, this is sufficient to get the solution. Marriott/Stuckey's "Programming with Constraints" is a good textbook, as is Apt/Wallace's "Constraint Logic Programming using Eclipse" – twinterer Feb 09 '12 at 11:33
  • Thanks for that direction as well, it really helps! Thank You. – kallakafar Feb 09 '12 at 15:56