我对我的CS任务有些麻烦。我试图调用之前在一个新规则中创建的另一条规则,该规则将计算幂函数的阶乘(例如Y =(N^X)!)。我认为我的代码的问题是exp(Y,X,N)中的Y在我称为阶乘(Y,Z)时没有继续,尽管我并不完全确定。我一直在试图找到一个这样的例子,但我一直无法找到任何东西。Prolog递归(功率函数的阶乘)
我不期待答案,因为这是家庭作业,但任何帮助将不胜感激。
这里是我的代码:
/* 1.2: Write recursive rules exp(Y, X, N) to compute mathematical function Y = X^N, where Y is used
to hold the result, X and N are non-negative integers, and X and N cannot be 0 at the same time
as 0^0 is undefined. The program must print an error message if X = N = 0.
*/
exp(_,0,0) :-
write('0^0 is undefined').
exp(1,_,0).
exp(Y,X,N) :-
N > 0, !, N1 is N - 1, exp(Y1, X, N1), Y is X * Y1.
/* 1.3: Write recursive rules factorial(Y,X,N) to compute Y = (X^N)! This function can be described as the
factorial of exp. The rules must use the exp that you designed.
*/
factorial(0,X) :-
X is 1.
factorial(N,X) :-
N> 0, N1 is N - 1, factorial(N1,X1), X is X1 * N.
factorial(Y,X,N) :-
exp(Y,X,N), factorial(Y,Z).
注意,您会在'factorial/3'的主体中得到一个关于'Z'的单例变量警告。你的问题可能在那里。如果你得到一个单例错误警告,并且你不知道该怎么做,请尝试用'_'替换该变量。如果由此产生的表达没有意义,你可以告诉你有更深的问题。 –
@DanielLyons好了,所以我解决了你现在提出的问题,看起来问题似乎是程序执行X^N,但是它不会继续计算它的阶乘。 – Jordanthedud
尝试使用'trace'来调试它。我的期望是,你有一个有趣的顺序变量,你可能意味着像'factorial(Y,X,N): - exp(F,X,N),阶乘(Y,F)'。 –