为什么 F# 函数在调用之前先求值? [英] Why do F# functions evaluate before they are called?

查看:27
本文介绍了为什么 F# 函数在调用之前先求值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我这样定义一个模块:

If I define a module as such:

module Module1
open System

let foo =
    Console.WriteLine("bar")

然后,在交互中做

#load "Library1.fs" //where the module is defined
open Module1

我看到一个

[正在加载 c:usersjjdocumentsvisual studio 2015ProjectsLibrary1Library1Library1.fs]酒吧

[Loading c:usersjjdocumentsvisual studio 2015ProjectsLibrary1Library1Library1.fs] bar

表明 foo 函数运行时我什至没有调用它!

Indicating that the foo function ran without me even calling it!

如何/为什么会发生这种情况?有什么办法可以防止吗?

How/why does this happen? Is there any way to prevent it?

我知道 foo 的返回值是 (Console.Writeline("bar")) 求值的任何值,并且没有任何理由不能立即"求值?(我猜当模块被加载时?) - 但是有没有办法防止它发生?如果我的模块函数改变了其他一些东西的状态,我能确保它们在被调用之前不求值吗?

I'm aware that the return value of foo is whatever (Console.Writeline("bar")) evaluates to, and that there isn't any reason that can't be evaluated "immediately?" (when the module is loaded I guess?) - but is there a way to prevent it from happening? If my module functions alter the state of some other stuff, can I ensure that they do not evaluate until called?

推荐答案

函数体在调用函数时被评估,就像你想要的那样.你的问题是 foo 不是一个函数,它是一个变量.

Function bodies are evaluated when the function is called, just as you want. Your problem is that foo is not a function, it's a variable.

要使foo成为一个函数,你需要给它参数.由于没有给它有意义的参数,单位值 (()) 将是常规参数:

To make foo a function, you need to give it parameters. Since there are no meaningful parameters to give it, the unit value (()) would be the conventional parameter:

let foo () =
    Console.WriteLine("bar")

相应地,这个函数的调用看起来像foo().

Accordingly a call of this function would look like foo ().

这篇关于为什么 F# 函数在调用之前先求值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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