I have the following snippet of prolog code:
num(0).
num(X) :- num(X1), X is X1 + 1.
fact(0,1) :-!.
fact(X,Y) :- X1 is X-1, fact(X1,Y1), !, Y is Y1 * X.
fact(X) :- num(Y), fact(Y,X).
Can somebody please explain why the following command causes a stack overflow? Thanks in advance.
fact(6).
First, looking at the rules
the predicate
num(Y)will be immediately valid forY = 0.Thus the rule
can be simplified as
that will find a match for
fact(0,1). ForX = 6, what happens instead is, as no rule defines a predicate forfact(0,6), a search is started withfact(-1,V1), followed withfact(-2,V2)etc… until a match occurs for afact(-value, Var)where the local result would be the Var found.This cannot happen, and an infinite loop consumes the whole stack, until an error is triggered.