Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoiding the use of cut in Prolog absolute value predicate

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 ("!")?

like image 320
Olhovsky Avatar asked Jan 26 '11 19:01

Olhovsky


People also ask

How do you negate a predicate in Prolog?

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).

How do you stop an execution in Prolog?

If you want to exit SWI-Prolog, issue the command halt., or simply type CTRL-d at the SWI-Prolog prompt.

What does \+ mean in Prolog?

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.

How do you fail in Prolog?

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).


1 Answers

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.

like image 60
hardmath Avatar answered Sep 19 '22 23:09

hardmath