From the article:|
Calculating the factorial:
% fac(N,R) : R is the factorial of N.
fac(N,R) :- P is N-1, fac(P,Q), R is N*Q.
Using this pattern is simple: typing the query fac(5,R)., for example, gives the result: R = 120. When playing around a little, though, many deficiencies start becoming apparent, including unwanted infinite loops and the fact that fac(N,120) doesn't give the expected result. The reason for this is the fact that Prolog is very ill-suited for numerical computation; arithmetic in Prolog is a hack, and doesn't integrate well into the Prolog search engine too well.
Wrong and misleading! The "unwanted infinite loop" is a consequence of the second
clause being incorrect: it does not state a logical truth. Adding 'N>0' to it would make
it correct and would end all infinite loops. The "arithmetic is a hack" phrase is both
incorrect and misleading. In fact, the only issue is that basic arithmetic in Prolog is
directional: 'Var is Expr' evaluates the term Expr as an expression and unifies the
result with Var. Nondirectional arithmetic is possible; it is done routinely by
constraint programming systems.
The author tries valiantly (and does say some right things), but be careful: he gets
some of the simple ideas wrong!