Solve extremely simple equation in prolog: A = B + C?

♀尐吖头ヾ 提交于 2019-12-23 14:42:50

问题


I have an extremely simple equation that I would like to be able to solve in prolog:

A = B + C

I'd like to be able to write a predicate expressing this relation, that can handle any one of the arguments not being instantiated. There is no need to generalize to more complex relations or equations.

myEquation(A, B, C) :-
...something...

That I could call with the following semantics:

myEquation(A,1,2).
>    A = 3.
myEquation(3,B,2).
>    B = 1.
myEquation(3,1,C).
>    C = 2.

Any ideas? Working with arithmetic operators yields a lot of "Arguments are not sufficiently instantiated" errors. It looks like solving arbitrary systems of equations is beyond the scope of most prolog implementations, but I'm hoping that this extremely simple equation is tractable.


回答1:


Not particularly fancy, but here it is. If you're not an absolute beginner, you could have done this too:

myEquation(A, B, C):- 
    var(A),number(B),number(C) -> A is B+C;
    var(B),number(A),number(C) -> B is A-C;
    var(C),number(A),number(B) -> C is A-B;
    A =:= B + C.

update: The same with Constraint Logic Programming:

:- use_module(library(clpq)).

myEquation(A, B, C):-
    {A = B + C}.



回答2:


If your domain is integers, use clpfd!

:- use_module(library(clpfd)).

:- assert(clpfd:full_answer).       % for SICStus Prolog

myEquation(A,B,C) :-
   A #= B+C.

Some sample queries with sicstus-prolog, version 4.3.2:

?- myEquation(A,B,C).
B+C#=A, A in inf..sup, B in inf..sup, C in inf..sup ? ;
no

?- myEquation(A,2,C).
2+C#=A, A in inf..sup, C in inf..sup ? ;
no    

?- myEquation(X,X,X).
X+X#=X, X in inf..sup ? ;
no

Let's run the same queries with swi-prolog, version 7.3.3:

?- myEquation(A,B,C).
B+C#=A.

?- myEquation(A,2,C).
2+C#=A.

?- myEquation(X,X,X).
X = 0.                              % succeeds deterministically


来源:https://stackoverflow.com/questions/26369666/solve-extremely-simple-equation-in-prolog-a-b-c

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