I have been thinking over this the whole day. I finally admit, I do not understand Prolog as good as I thought.
At the start of the day, I had trouble implementing a successor arithmetic, which multiplies 2 s-Numbers, which structure is this:
nat(0).
nat(s(X)):-nat(X).
My first try was this:
mul(0,_,0).
mul(s(F1),F2,P):-mul(F1,F2,Tmp),add(F2,Tmp,P)
which worked, but the query mul(X,Y,s(0))
ended in an infinite loop. Why?
I have read the following post: Prolog successor notation yields incomplete result and infinite loop
What I understood out of it: If I call mul before calling add, and I have variables in the mul/3 predicate which are NOT used in both mul/3 calls, Prolog tries to find new possibilties for the variables it did not bind. Therefore it goes into an infinite loop.
To solve the problem, I called add first:
mul(0,_,0).
mul(s(F1),F2,P):-add(F2,Tmp,P),mul(F2,F1,Tmp).
That did it. Then i tried to implement the power function, and thought "Well, that's easy now, first try would be:
pow(_,0,s(0)).
pow(B,s(E),R):-pow(B,E,Tmp), mul(Tmp,B,R).
But, I have to put mul first to prevent the left-recursion of R and Tmp.
Easy!" Boy, I was so wrong. I have no idea how to implement it without getting in an infinite loop, even if I put the mul in front.
Any advice is highly appreciated. You can save my saturday work effort and boost my self-esteem! Thank you in advance.
Edit: Added my missing sum predicate:
add(0, Y, Y).
add(s(S1), S2, s(Sum)):- add(S1,S2,Sum).