Prolog递归n个自然数的总和

时间:2018-04-09 17:06:16

标签: prolog

我很难理解Z的价值是如何不断变化的。已在堆栈跟踪输出中指示了特定步骤。

以下是我用于查找N个自然数之和的代码 -

sum1(1,1).
sum1(N, Sum) :-
   Next is N-1,
   sum1(Next, Z),
   Sum is Z + N.

这是堆栈跟踪 -

?- sum1(3,_).
   Call: (8) sum1(3, _2668) ? creep
   Call: (9) _2860 is 3+ -1 ? creep
   Exit: (9) 2 is 3+ -1 ? creep
   Call: (9) sum1(2, _2862) ? creep
   Call: (10) _2866 is 2+ -1 ? creep
   Exit: (10) 1 is 2+ -1 ? creep
   Call: (10) sum1(1, _2868) ? creep
   Exit: (10) sum1(1, 1) ? creep
   Call: (10) _2872 is 1+2 ? creep
   Exit: (10) 3 is 1+2 ? creep
   Exit: (9) sum1(2, 3) ? creep **%How is Z assigned value 3 ?**
   Call: (9) _2668 is 3+3 ? creep
    Exit: (9) 6 is 3+3 ? EOF: exit

提前致谢!

1 个答案:

答案 0 :(得分:1)

不是“改变”; sum1的每个证明都有自己的NSumNextZ版本。这就是为什么在堆栈跟踪中,每个都获得一个不同的生成名称(即_2860),因此Prolog可以区分它们。

关于您的具体问题,您询问的行上方有2行,特定Sum_2872;因此,_2872 is 1+2要求_2872要求Sum为3.此sum(1, _2868)与之前的_2868匹配,其中sum1Z' s def std1(): stud=input('Enter Student name') crs=[] crst=int(input('How many courses you want to enter')) for i in range(crst): EnterCourse = input('Course') crs.append(str(EnterCourse)) stdrec1=(stud,crs) return main() def std2(): stud=input('Enter Student name') crs=[] crst=int(input('How many courses you want to enter')) for i in range(crst): EnterCourse = input('Course') crs.append(str(EnterCourse)) stdrec2=(stud,crs) def main(): print(""" Welcome to the Student Database [1] = Enter Student Record [2] = Enter Second Student Record [3] = Enter Third Student Record [4] = Print the record """) action = input('What Would you like to do today? (Enter number to Continue) ') if action == '1': std1() elif action == '2': print('2') elif action == '3': print('3') elif action == '4': print(#all the list together) else: print('Error! Wrong Menu Selected | Calling the FBI now') (从上面2行可以看出)。