F#代码执行顺序 [英] F# Code Execution Order

查看:82
本文介绍了F#代码执行顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

另一个有关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?

推荐答案

ExeAExeC不是函数,而是单个值.编译器确保值按照在源文件中声明的顺序进行初始化,所以这里发生的是:

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:

  1. ExeC初始化
  2. ExeA初始化
  3. 使用ExeA的初始化值打印
  4. Example 1
  5. ExeB函数通常被称为
  6. 使用ExeC的初始化值来打印
  7. Example 3
  1. ExeC initialises
  2. ExeA initialises
  3. Example 1 is printed, using ExeA's initialised value
  4. The ExeB function is called as normal
  5. Example 3 is printed, using ExeC's initialised value

如果您希望ExeAExeC真正懒惰(即控制它们的副作用何时发生),则可以将它们变成接受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屋!

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