I have implemented the following function in 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 the use of cut ("!")?
To cut or not to cut - NegationThe negation predicate in prolog is \+ and therefore \+ round(earth) returns true. This limitation of prolog that is a goal cannot be proved then it is false, is called the close world assumption (CWA).
If you want to exit SWI-Prolog, issue the command halt., or simply type CTRL-d at the SWI-Prolog prompt.
Because of the problems of negation-as-failure, negation in Prolog is represented in modern Prolog interpreters using the symbol \+ , which is supposed to be a mnemonic for not provable with the \ standing for not and the + for provable.
fail/0 is a special symbol that will immediately fail when prolog encounters it as a goal. fail is often used in conjunction with CUT(!) to enforce failure. like(me,X) :- chess(X),!,fail. like(me,X) :- games(X).
There's the "hidden" cut in the if-then-else construct of Prolog:
abs2(X,Y) :- X < 0 -> Y is -X ; Y = X.
It is something of a quirk, but Prolog does not backtrack on the subgoal that forms the "premise" of an if-then or if-then-else construct. Here, if X < 0 succeeds the first try, then the choice of "then" clause over "else" clause is committed (hence the description of this behavior as a "hidden" cut).
There is more of a role for a cut in the first clause of the predicate abs2/2 as written in the question. As Nicholas points out, the cut at the end of the second clause doesn't have any effect (there are no choice points left when you get there). But as Kaarel points out, there is a choice point left open if the first clause succeeds.
So what I would have written, allowing the use of a cut, is this:
abs2(X,X) :- X >= 0, !.
abs2(X,Y) :- Y is -X.
Nicholas's comments also suggest ways to "arithmetize" the absolute value (rather than use a logic definition) and avoid "cut" that way.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With