1
gcd(X,X,X):-
    !.
gcd(X,Y,Z):-
    X>Y,
    !,
    Inter is X - Y,
    gcd(Inter, Y, Z).
gcd(X,Y,Z):-
    Inter is Y - X,
    gcd(X,Inter,Z).

I get the if else nature of the second cut but I don't understand why program just aborts with the first cut.

false
  • 10,264
  • 13
  • 101
  • 209
Lin
  • 47
  • 5

1 Answers1

1

It just means you've reached a state where you can get rid of all possible other solutions. Otherwise when asking for more solutions Prolog would run the third rule resulting in unwanted answers. You could alternatively rewrite it like this (assuming X and Y are unified):

gcd(X,X,X).
gcd(X,Y,Z):-
    X>Y,
    Inter is X - Y,
    gcd(Inter, Y, Z).
gcd(X,Y,Z):-
    X<Y,
    Inter is Y - X,
    gcd(X,Inter,Z).

The version with the cuts runs probably faster because it does not require as much RAM as the version without cuts. But the version without cuts does not require the strict order of the rules.

DuDa
  • 3,718
  • 4
  • 16
  • 36
  • It's not necessarily slower without cuts - if the pattern is `=:=`, `<`, `>` the compiler might see the case distinction (the code only works for ground terms anyway) such that it could optimize. – lambda.xy.x Nov 30 '21 at 14:28
  • `gcd(1,1,0).` does not run faster in the original version - quite the opposite. – false Nov 30 '21 at 18:11