Prolog trying values until they are correct and then return them

时间:2018-12-04 23:03:58

标签: prolog

I am trying to do a rule in Prolog, where I check if it fits, if it does not, I increase and check again until it fits. But my problem is that when I find out the numbers where it fits and try to return them, the original numbers stay the same.

** Please note that this is not the original rule, mine is a lot longer and would be too much to write here, but I tried to make it as simple as possible.
Also the structure must remain the same.

make_it_fit(X,Y):-
    does_it_fit(X, Y),
    write(['Nums ', X,Y]).

%--- Check if fits, if not then increase number and check until fits
does_it_fit(X,Y):-
   (fits(X,Y));
   (find_new(X,Y,X1,Y1),does_it_fit(X1,Y1)).

So when I call :

?- make_it_fit(5,5).

It goes to the does_it_fit(5,5), does the fits(5,5), finds out that it does not fit, increases the numbers to (6,6) and calls the does_it_fit(6,6), then it checks the fits(6,6), finds out that it does fit and returns.

Now when I am writing out the results just to see them, It still prints out the (5,5), not (6,6).

What am I doing wrong here?

If I did not explain it clearly enough, then do tell and I will try to explain it further.

1 个答案:

答案 0 :(得分:1)

您的问题实质上是您期望X和Y在对does_it_fit/2的调用期间以某种方式重新分配,并且随后获得了新的值。但是Prolog变量不是“可分配的”变量,它们的工作方式更像数学中的变量,因此您将需要提供另一组变量才能放置结果。

does_it_fit(X, Y, X , Y ) :- fits(X, Y). 
does_it_fit(X, Y, XN, YN) :- 
    \+ fits(X,Y), 
    find_new(X, Y, X1, Y1), 
    does_it_fit(X1, Y1, XN, YN).

然后对make_it_fit/2的调用也必须更改:

make_it_fit(X,Y):-
    does_it_fit(X, Y, XN, YN),
    write(['Nums ', XN, YN]).