F#代码执行顺序 [英] F# Code Execution Order
问题描述
另一个有关F#的菜鸟问题.
another noob question regarding F#.
如果我有以下代码...
If I have the following code...
let ExeC =
printfn "c"
3
let ExeB b =
printfn "b"
2
let ExeA =
printfn "a"
1
printfn "Example %d " ExeA
printfn "Example %d " (ExeB 1)
printfn "Example %d " ExeC
输出如下...
c
a
Example 1
b
Example 2
Example 3
在这里看起来不寻常的是代码的执行顺序.在上一个问题中,Brian提到了一些有关表达式的内容,我希望有人能对此做更多解释.似乎编译器似乎已经在智能地预执行一些事情来计算值...但我不知道吗?
What seems unusual here is the order that the code is executing in. In a previous question Brian mentioned something about expressions, I was hoping someone could explain this a bit more. It almost seems like the compiler is intelligently pre-executing things to calculate values... but I don't know?
推荐答案
ExeA
和ExeC
不是函数,而是单个值.编译器确保值按照在源文件中声明的顺序进行初始化,所以这里发生的是:
ExeA
and ExeC
aren't functions, but single values. The compiler ensures that values initialise in the order in which they're declared in the source file, so what's happening here is:
-
ExeC
初始化 -
ExeA
初始化
使用 -
Example 1
-
ExeB
函数通常被称为
使用 -
Example 3
ExeA
的初始化值打印ExeC
的初始化值来打印ExeC
initialisesExeA
initialisesExample 1
is printed, usingExeA
's initialised value- The
ExeB
function is called as normal Example 3
is printed, usingExeC
's initialised value
如果您希望ExeA
和ExeC
真正懒惰(即控制它们的副作用何时发生),则可以将它们变成接受unit
的函数:
If you want ExeA
and ExeC
to be truly lazy -- that is, to control when their side effects run -- you could turn them into functions that accept unit
:
let ExeC () =
printfn "c"
3
let ExeB b =
printfn "b"
2
let ExeA () =
printfn "a"
1
printfn "Example %d " (ExeA ())
printfn "Example %d " (ExeB 1)
printfn "Example %d " (ExeC ())
这篇关于F#代码执行顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!