I've just tried to implement absolute function in Prolog and I've got some strange behavior. My code was:
absval(X, RESULT) :- X >= 0, RESULT is X.
absval(X, RESULT) :- X < 0, RESULT is -X.
And when I try in SWI-Prolog absval(-2,X).
I get
X = 2
yes
as expected. But otherwise when I invoke absval(2,X)
, I get X = 2 ?
and I should insert another input. After pressing enter I get also yes
.
What does mean the second one result? What's wrong with my solution?
absval/2
. So, after Prolog satisfiesabsval(2,X)
using the first rule, it backtracks in order to resatisfy the goal. The first subgoal(X < 0)
of the second rule will fail and you will not get a second solution. In order to have a deterministic behavior, add a cut operator afterX>=0
like this:absval(X, RESULT) :- X >= 0, !, RESULT is X.
. – Tudor Berariu