compute the n'th fibonacci number in Ocaml

计算斐波那契数,最简单的计算当然是按照定义来求解了,

f0=0, f1=1, fn = fn-1 + fn-2。直接递归实现的话效率比较地下,可以考虑使用迭代的方法来求解。

代码如下

1 let fib n =
2     let rec fib_int a b count =
3       if count = 1 then a else fib_int (a+b) a (count-1)
4     in
5     if n = 0 then 0 else fib_int 1 0 n ;;

里面使用了一个fib_int的内部过程来模拟循环。

原文地址:https://www.cnblogs.com/mathlover/p/2789811.html