How to do arithmetic expression evaluation in prolog?

£可爱£侵袭症+ 提交于 2019-12-23 03:46:14

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!