Avoiding Using a Slice in a Prolog Absolute Value Predicate

I implemented the following function in the prolog with the following code:

abs2(X, Y) :- X < 0, Y is -X.
abs2(X, X) :- X >= 0, !.

How can I implement this function without using cut ("!")?

+5
source share
3 answers

There is a "hidden" section in the if-then-else Prolog construct:

abs2(X,Y) :- X < 0 -> Y is -X ; Y = X.

This is a bit of a quirk, but Prolog does not return to the subtitle that forms the "premise" of the if-then or if-then-else construct. Here, if X <0 succeeds on the first attempt, then the selection of the β€œthen” clause over the else clause is performed (therefore, the description of this behavior as a β€œhidden” cut).

abs2/2, . , ( , , ). , , , , .

, , :

abs2(X,X) :- X >= 0, !.
abs2(X,Y) :- Y is -X.

"" ( ) "" .

+8

, ? , , :

abs(X, Y) :- number(X) , X <  0 , Y is -X .
abs(X, X) :- number(X) , X >= 0 .
+5
source

No need to use !

Just write:

abs2(X,Y) :- Y is abs(X).
+3
source

All Articles