One unknown linear equation using Prolog

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

I tried to do this by splitting the lines to get everything I need to solve the equation, but I'm sure there is a better way.

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

This is what I am trying to solve. I want to use solve / 1.

Thanks in advance.

+4
source share
1 answer

You can 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 this problem without libraries, you can 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 examples:

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

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

Source: https://habr.com/ru/post/1655396/


All Articles