这个“()"符号是什么意思? [英] What does this '()' notation mean?
问题描述
我刚开始学习 F#.本书使用以下符号:
I just started to learn F#. The book uses the following notation:
let name() = 3
name()
与此不同的是:
let name = 3
name
?
推荐答案
在回答 ()
是什么之前,让我们先定义一些基础知识并完成一些示例.
Before answering what ()
is lets get some basics defined and some examples done.
在 F# 中,let 语句 具有名称、零或更多参数和一个表达式.
In F# a let statement has a name, zero or more arguments, and an expression.
为了保持简单,我们将采用:
如果没有参数,那么 let 语句是一个值.
如果有参数,那么 let 语句是一个函数.
To keep this simple we will go with:
If there are no arguments then the let statement is a value.
If there are arguments then the let statement is a function.
对于一个值,表达式的结果只计算一次并绑定到标识符;它是不可变的.
对于函数,每次调用函数时都会计算表达式.
For a value, the result of the expression is evaluated only once and bound to the identifier; it is immutable.
For a function, the expression is evaluated each time the function is called.
所以这个值
let a = System.DateTime.Now;;
总是有第一次评估或稍后调用的时间,即
will always have the time when it is first evaluated or later invoked, i.e.
a;;
val it : System.DateTime = 1/10/2017 8:16:16 AM ...
a;;
val it : System.DateTime = 1/10/2017 8:16:16 AM ...
a;;
val it : System.DateTime = 1/10/2017 8:16:16 AM ...
还有这个功能
let b () = System.DateTime.Now;;
每次评估时总会有一个新的时间,即
will always have a new time each time it is evaluated, i.e.
b ();;
val it : System.DateTime = 1/10/2017 8:18:41 AM ...
b ();;
val it : System.DateTime = 1/10/2017 8:18:49 AM ...
b ();;
val it : System.DateTime = 1/10/2017 8:20:32 AM ...
现在解释()
的含义.请注意,System.DateTime.Now
不需要参数即可工作.
Now to explain what ()
means. Notice that System.DateTime.Now
needs no arguments to work.
当表达式不需要参数时,我们如何创建函数?
How do we create a function when the expression needs no arguments?
每个参数都必须有一个类型,所以 F# 有 单元类型 用于不需要参数且单元类型的唯一值是 ()
的函数.
Every argument has to have a type, so F# has the unit type for functions that need no arguments and the only value for the unit type is ()
.
所以这是一个函数,只有一个参数 x
,类型为 int
So this is a function with one argument x
of type int
let c x = x + 1;;
这是一个带有一个参数 ()
的函数,类型为 unit
and this is a function with one argument ()
of type unit
let b () = System.DateTime.Now;;
这篇关于这个“()"符号是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!