3

Consider this Prolog predicate:

silly:-
    1 = 1.
silly:-
    1 = 2.

When querying, the output answer has two states: true and then false. Is there anyway to ask Prolog to terminate as soon as it hits a true statement in a disjunction?

TuanDT
  • 1,627
  • 12
  • 26

2 Answers2

6

The question is "Is there anyway to ask Prolog to terminate as soon as it hits a true statement in a disjunction"?

The answer is "Use once/1 when querying for the answer".

For example:

     ?- [user] .
     silly:-
     1=1 .
     silly:-
     1=2 .
     silly:-
     2=2 .
     end_of_file .

     ?- %% query WITHOUT once {results in 2 answers} : %%
     silly .
     true ;
     true.

     ?- %% query WITH once {results in 1 answer} : %%
     once(silly) .
     true.

The use of cut ! does not meet the semantic requirements of the question as stated.

Using cut would be appropriate if the question had been more like "Is there anyway to ask tell Prolog to terminate as soon as it hits a true statement** a statement specially indicated* in a disjunction" ?

user229044
  • 232,980
  • 40
  • 330
  • 338
Kintalken
  • 763
  • 5
  • 9
  • 1
    A light bulb went off for me when I realised this is equivalent to `once(1=1;1=2;2=2)`. In other words, separate rules are just disjunction clauses, and `once` stops once it reaches one that succeeds. So it's also equivalent to defining `silly :- 1=1; 1=2; 2=2.` and calling `once(silly)`. Which as the other answer covers, is equivalent to `silly :- (1=1,!);(1=2,!);2=2.`. Handy when the leaves of knowledge form branches of a tree! – Heath Raftery May 20 '23 at 03:27
4

add a cut

silly:-
    1 = 1, !.
silly:-
    1 = 2.

or use if/then/else, but then the 'program' take a very different shape, being the alternative branches merged into a single clause. Also note that, as stated in documentation

Unlike !/0, the choice point of the predicate as a whole (due to multiple clauses) is not destroyed.

silly:-
    ( 1 = 1 -> true ; false ).
CapelliC
  • 59,646
  • 5
  • 47
  • 90
  • Ahh.. your solution is elegant! Gotta do some more reading about cuts. Thank you for the pointer. – TuanDT Aug 17 '14 at 13:11
  • 2
    Generally speaking, cuts are mostly used for implementing negation by failure. This is an interesting stackoverflow 'debate' on the appropriate use of Prolog cuts you might want to have a look at: http://stackoverflow.com/questions/14541164/knowing-when-to-use-cut-in-prolog – panza Nov 11 '15 at 10:38