functions calls order in OCaml

懵懂的女人 提交于 2019-12-08 07:36:56

问题


I discovered the trace function in OCaml to follow functions calls. I tried it with fibonacci however the order of function calls was not the one I was expecting. In my code I call fib (n - 1) first then fib (n - 2) but, with trace, it tells me that fib (n - 2) is actually called first. What is the reason?

let rec fib n = 
    if n < 2 then 1
    else fib (n - 1) + fib (n - 2);;

When I trace fib 3 I get:

fib <-- 3
fib <-- 1
fib --> 1
fib <-- 2
fib <-- 0
fib --> 1
fib <-- 1
fib --> 1
fib --> 2
fib --> 3
- : int = 3

回答1:


Your function contains: fib (n - 1) + fib (n - 2)

The order in which the operands of + are evaluated is unspecified. The bytecode OCaml compiler and the native OCaml compiler can even use different orders. For whatever reason, the compiler you used simply chose to generate code that evaluates fib (n - 2) first, then fib (n - 1), then computes the sum.



来源:https://stackoverflow.com/questions/35548589/functions-calls-order-in-ocaml

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!