函数在OCaml中调用顺序 [英] functions calls order in OCaml

查看:100
本文介绍了函数在OCaml中调用顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在OCaml中发现了跟踪函数来跟踪函数调用.我用fibonacci尝试过,但是函数调用的顺序不是我期望的.在我的代码中,我先调用fib (n - 1),然后调用fib (n - 2),但是通过跟踪,它告诉我实际上首先调用了fib (n - 2).是什么原因?

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);;

当我跟踪fib 3时,我得到:

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

推荐答案

您的函数包含:fib (n - 1) + fib (n - 2)

+的操作数的求值顺序未指定.字节码OCaml编译器和本机OCaml编译器甚至可以使用不同的顺序.无论出于何种原因,您使用的编译器只是选择生成先评估fib (n - 2),然后评估fib (n - 1),然后计算总和的代码.

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.

这篇关于函数在OCaml中调用顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆