2012-04-03 37 views

回答

9

可以通过references完成:

let fact n = 
    let result = ref 1 in (* initialize an int ref *) 
    for i = 2 to n do 
    result := i * !result (* reassign an int ref *) 
    done; 
    !result 

你看不到的引用非常频繁,因为你可以使用里面递归或高阶功能不变的价值观做同样的事情:

​​

无副作用的解决方案是首选,因为它们更容易推理,更容易确保正确性。

+0

谢谢。你能解释一下ref 0的含义吗? – EBM 2012-04-03 23:13:16

+3

请参阅我的答案中的链接。基本上'ref 0'是一个记录'{mutable contents:int}',其中'contents'由'0'初始化,'contents'可以在稍后重新分配。 – pad 2012-04-03 23:21:50