power_output
power_output

Reputation: 421

functions calls order in OCaml

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

Upvotes: 1

Views: 199

Answers (1)

Pascal Cuoq
Pascal Cuoq

Reputation: 80255

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.

Upvotes: 5

Related Questions