Egert Aia
Egert Aia

Reputation: 469

Linear equation with one unknown using Prolog

I am wondering how to solve basic linear equation with one unknown.

I tried doing it by string splitting in order to get everything i need to solve the equation, but i am sure there is a better way.

solve(5 + X = 10).
X = 5.
solve(5+8 = Ans).
Ans = 13.

This is the thing I'm trying to solve. I want to use solve/1.

Thank you in advance.

Upvotes: 3

Views: 595

Answers (1)

coder
coder

Reputation: 12982

You could write:

:- use_module(library(clpfd)).

solve(X+Y=Z):-X+Y#=Z.

Some examples:

?- solve(5+X=10).
X = 5.

?- solve(5+8=ANS).
ANS = 13.

To solve it without libraries you could write:

solve(S):-var(S),throw("instatiation error").
solve(X+Y=Z):-(var(X),var(Y);var(X),var(Z);
               var(Y),var(Z)),throw("instatiation error").
solve(X+Y=Z):-nonvar(Z),nonvar(Y),L is Z-Y,X=L.
solve(X+Y=Z):-nonvar(Z),nonvar(X),L is Z-X,Y=L.
solve(X+Y=Z):-nonvar(X),nonvar(Y),L is X+Y,Z=L.

and again the examples:

?- solve(5+X=10).
X = 5 ;
false.

?- solve(5+8=Ans).
Ans = 13.

Upvotes: 6

Related Questions