我试图理解为什么递归函数的行为方式。
let rec fact = function
|0 -> 1
|n -> n * fact(n-1);;
当我执行时:
fact 4;;
它回应:
val it : int = 24
当前是正确的,因为1 * 2 * 3 * 4 = 24
我没有得到的是这段代码:
|n -> n * fact(n-1);;
我不明白为什么不计算:
4 -> 4 * (4-1)
4 -> 4 * 3
4 -> 12
我的猜测我是否误解了n
的定义 有人能做到这一点并开导我吗?答案 0 :(得分:6)
如果定义是n -> n * (n - 1)
,但它正在对fact
进行递归调用,那将是真的,所以它是:
4 * fact(4 - 1)
=> 4 * fact(3)
=> 4 * (3 * fact(2))
=> 4 * (3 * (2 * fact(1)))
=> 4 * (3 * (2 * (1 * fact(0))))
=> 4 * (3 * (2 * (1 * 1)))
=> 4 * (3 * (2 * 1))
=> 4 * (3 * 2)
=> 4 * 6
=> 24
答案 1 :(得分:5)
它不计算// add warning message to received messages storage
receivedWarningMap[wsm->getTreeId()].push_back(wsm->dup());
std::cout<<"Wsm dup() values/ receivedWarningMap="<<wsm->dup()<<endl;
std::ofstream tracefile;
tracefile.clear();
tracefile.open("traceFile1.txt", std::ios_base::app);
for (UINT i = 0; i < receivedWarningMap[wsm->getTreeId()].size(); i++)
{
std::cout << receivedWarningMap[wsm->getTreeId()][i] << std::endl;
EV<< "MyID="<<getMyID()<< "Recepient ID"<<wsm->getRecipientAddress()<<"Neighbor ID="<< wsm->getSenderAddress()<< std::endl;
,因为代码不是4 * (4-1)
。它是n * (n-1)
,因此会计算n * fact (n-1)
,即:
4 * fact (4 - 1)
依此类推,直到你最终得到 4 * fact (4 - 1)
= 4 * fact 3
= 4 * (function | 0 -> 1 | n -> n * fact (n-1)) 3
= 4 * (match 3 with | 0 -> 1 | n -> n * fact (n-1))
= 4 * 3 * fact (3 - 1)
= 4 * 3 * fact 2
...
。
答案 2 :(得分:0)
我想我现在知道了!
fact 4;;
fun 4 match 4 with |0 -> 1|n -> n * fact(n-1)
|0 -> 1|4 -> 4 * fact(4-1)
|false |4 -> 4 * fact(3)
|false |4 -> 4 * fun 3 match 3 with |0 -> 1|n -> n * fact(n-1)
|false |4 -> 4 * |0 -> 1|3 -> 3 * fact(3-1)
|false |4 -> 4 * |false |3 -> 3 * fact(2)
|false |4 -> 4 * |false |3 -> 3 * fun 2 match 2 with |0 -> 1|n -> n * fact(n-1)
|false |4 -> 4 * |false |3 -> 3 * |0 -> 1|2 -> 2 * fact(2-1)
|false |4 -> 4 * |false |3 -> 3 * |false |2 -> 2 * fact(1)
|false |4 -> 4 * |false |3 -> 3 * |false |2 -> 2 * fun 1 match 1 with |0 -> 1|n -> n * fact(n-1)
|false |4 -> 4 * |false |3 -> 3 * |false |2 -> 2 * |0 -> 1|1 -> 1 * fact(1-1)
|false |4 -> 4 * |false |3 -> 3 * |false |2 -> 2 * |false |1 -> 1 * fact(0)
|false |4 -> 4 * |false |3 -> 3 * |false |2 -> 2 * |false |1 -> 1 * fun 0 match 0 with |0 -> 1|n -> n * fact(n-1)
|false |4 -> 4 * |false |3 -> 3 * |false |2 -> 2 * |false |1 -> 1 * |true|
4 -> 4 * 3 -> 3 * 2 -> 2 * 1 -> 1 * 0 -> 1 = 24