Search code examples
prologfailure-slice

Prolog: Error out of global stack with what looks like ONE level of recursion to me


I am quite rusty in prolog, but I am not sure why things like this fail:

frack(3).

frack(X) :- frack(X-1).

So, if I evaluate frack(4). from the interactive prompt with the above facts defined, I expect that it should not have to endlessly recurse, since 4-1 = 3. But I get this error in SWI-Prolog:

ERROR: Out of global stack

Solution

  • Try it:

    ?- 4-1 = 3.
    false.
    

    Why? Because 4-1 = -(4, 1), which clearly is not a number but a compound term.

    To reason about integers in Prolog, use constraints, for example (using GNU Prolog or B-Prolog):

    | ?- 4-1 #= X.
    
    X = 3
    

    In SWI-Prolog, the graphical tracer may be useful for you to see what happens:

    ?- gtrace, frack(4).
    

    For more complex debugging, I recommend as shown in false's answer.