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.
Numbers in PrologNumbers are used like constants, and represented like they are anywhere on the computer, the following are valid ways of dealing with numbers in a predicate: a(12, 345). a(A) :- b(A, 234.3). a(345.3409857) :- b(23476.923804).
TOPIC : PROLOG PROGRAMS Write a prolog program to calculate the sum of two numbers. sum(X,Y,Z):- Z is X+Y. max(X,Y,M):-X>Y,M is X. max(X,Y,M):-Y>=X,M is Y.
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}.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With