Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 489
Juanjo Conti Avatar asked Feb 03 '23 08:02

Juanjo Conti


2 Answers

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

like image 93
Stephan202 Avatar answered Feb 21 '23 01:02

Stephan202


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.

like image 32
starblue Avatar answered Feb 21 '23 00:02

starblue