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?
what you report doesn't match the behaviour I get here:
?- absval(2,X).
X = 2 ;
false.
that's actually what is expected.
If you need to make it deterministic, use a cut, or better, the 'if/then/else' construct:
absval(X, RESULT) :- X >= 0 -> RESULT is X ; RESULT is -X.