为什么F#函数在被调用之前进行评估? [英] Why do F# functions evaluate before they are called?

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

问题描述

 模块Module1 
打开系统

让foo =
Console.WriteLine(bar)

然后,

  #loadLibrary1.fs//定义模块
open Module1
code>

我看到一个


[正在加载c:\ users \jj\documents\visual studio 2015\Projects\Library1\Library1\Library1.fs)
bar


表明foo函数在我没有调用的情况下运行!



这是怎么发生的?有什么办法可以防止它?



我知道foo的返回值是任何(Console.Writeline(bar))的计算结果,没有任何理由不能立即评估? (当模块被加载时,我猜?) - 但有没有办法阻止它发生?如果我的模块功能改变了其他一些东西的状态,我可以确保它们在被调用之前不进行评估吗?

解决方案

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



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

  let foo()= 
Console.WriteLine(bar)

因此,这个函数的调用看起来像 foo()


If I define a module as such:

module Module1
open System

let foo =
    Console.WriteLine("bar")

Then, in interactive do

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

I see a

[Loading c:\users\jj\documents\visual studio 2015\Projects\Library1\Library1\Library1.fs] bar

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

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

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?

解决方案

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.

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

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

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

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