Juanjo Conti
Juanjo Conti

Reputation: 30023

What's the -> operator in Prolog and how can I use it?

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?

Upvotes: 10

Views: 14917

Answers (3)

Stephan202
Stephan202

Reputation: 61529

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

Upvotes: 11

starblue
starblue

Reputation: 56772

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:

?- member(X,[1,2,3]), (X=1 -> Y=a ; X=2 -> Y=b ; Y=c).
X = 1,
Y = a ;
X = 2,
Y = b ;
X = 3,
Y = c.

?- member(X,[1,2,3]), (X=1, !, Y=a ; X=2 -> Y=b ; Y=c).
X = 1,
Y = a.

Therefore it is called a local cut.

Upvotes: 3

pfctdayelise
pfctdayelise

Reputation: 5285

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.

Upvotes: 1

Related Questions