简体   繁体   English

Prolog 使用递归的阶乘

[英]Prolog Factorial using recursion

I can't seem to wrap my head around how this works, to be specific I don't understand how F1 represents the value of (N-1).我似乎无法理解这是如何工作的,具体来说,我不明白 F1 如何表示 (N-1) 的值。 cause the way I see it once we reach the base case the value of F1 stays at 1 seeing as to how it is never reassigned.因为我看到它的方式,一旦我们达到基本情况,F1 的值就保持在 1,看看它是如何永远不会重新分配的。 I just want to understand for instance if N = 4 , how once we reach the base case the value of F1 goes from 1 to 2 to 6.我只想了解,例如,如果N = 4 ,一旦我们达到基本情况,F1 的值如何从 1 变为 2 再到 6。

factorial(0,1).   

factorial(N,F) :-    
   N>0,   
   N1 is N-1,   
   factorial(N1,F1),   
   F is N * F1.

the value of F1 stays at 1 F1的值保持为 1

how the value of F1 F1的值如何

The secret is that you need plural not singular;秘诀是你需要复数而不是单数; when running your code, Prolog makes many variables named F1 , one for each intermediate value.运行代码时, Prolog 生成许多名为F1的变量,每个中间值一个。 Each call to factorial(N1, F1) adds a new layer to the call stack , with a new copy of all the variables which factorial/2 uses.每次调用factorial(N1, F1)都会向调用堆栈添加一个新层,其中包含factorial/2使用的所有变量的新副本。 They have the same names, but they are separate in memory and can be bound to different values.它们具有相同的名称,但它们在 memory 中是分开的,并且可以绑定到不同的值。

This is the same stack which can grow too big in unbounded recursion and overflow, giving a stackoverflow error, the name of this website.这是同一个堆栈,它在无界递归和溢出中会变得太大,从而给出一个 stackoverflow 错误,这个网站的名称。

F    is 4 * F1_a
F1_a is 3 * F1_b
F1_b is 2 * F1_c
F1_c is 1 * F1_d
F1_d = 1

The stack is built up in memory, then when the base case is reached the code can move on to F is N * F1.堆栈建立在 memory 中,然后当达到基本情况时,代码可以继续执行F is N * F1. and the stack collapses down and the intermediate F1 s are cleared out.堆栈崩溃,中间的F1被清除。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM