views:

100

answers:

3

I've read about it in a book but it wasn't explained at all. I also never saw it in a program. Is part of Prolog syntax? What's it for? Do you use it?

Thanks

+2  A: 

It represents implication. The righthand side is only executed if the lefthand side is true. Thus, if you have this code,

implication(X) :-
  (X = a ->
    write('Argument a received.'), nl
  ; X = b ->
    write('Argument b received.'), nl
  ;
    write('Received unknown argument.'), nl
  ).

Then it will write different things depending on it argument:

?- implication(a).
Argument a received.
true.

?- implication(b).
Argument b received.
true.

?- implication(c).
Received unknown argument.
true.

(link to documentation.)

Stephan202
+1  A: 

It's a local version of the cut, see for example the section on control predicated in the SWI manual.

It is mostly used to implement if-then-else by (condition -> true-branch ; false-branch). Once the condition succeeds there is no backtracking from the true branch back into the condition or into the false branch, but backtracking out of the if-then-else is still possible. Therefore it is called local cut or soft cut.

starblue
A: 

It is possible to avoid using it by writing something more wordy. If I rewrite Stephan's predicate:

implication(X) :-
  (
    X = a,
    write('Argument a received.'), nl
  ; 
    X = b,
    write('Argument b received.'), nl
  ;
    X \= a,
    X \= b,
    write('Received unknown argument.'), nl
  ).

(Yeah I don't think there is any problem with using it, but my boss was paranoid about it for some reason, so we always used the above approach.)

With either version, you need to be careful that you are covering all cases you intend to cover, especially if you have many branches.

ETA: I am not sure if this is completely equivalent to Stephan's, because of backtracking if you have implication(X). But I don't have a Prolog interpreter right now to check.

pfctdayelise
Hmm. I'm not so much into Prolog, but this appears to violate the DRY principle. Not sure if that's worth it! I mean, especially if the preconditions become slightly more complex, this may get messy. As for backtracking: for this version (SWI-)prolog does not immediately return to the prompt on `implication(a)` and `implication(b)`, so indeed some backtracking will be attempted.
Stephan202
Yeah I'm definitely not saying this is a superior alternative, just that it is an alternative. :)
pfctdayelise