Search code examples
prologswi-prolog

Prolog assignment fails


I am trying to build a simple greatest common divisor (cmmdc) in prolog and, for the following code, I get a fail on newY = X mod Y. Can anyone help me out?

% cmmdc(X: intreg, Y: intreg, Ret: intreg)
% (i, i, o), (i, i, i)

cmmdc(X, 0, X):- !.
cmmdc(X, Y, Ret):-
    newY = X mod Y,
    cmmdc(Y, newY, Ret).

Solution

  • newY starts with a lowercase letter, so it is an atom instead of a varaible.

    = is unification, not arithmetic.

    The atom newY is not the same as the term mod(X,Y) so unification fails.

    Use NewY is X mod Y instead.