Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
772 views
in Technique[技术] by (71.8m points)

function - What does this '()' notation mean?

I just started to learn F#. The book uses the following notation:

let name() = 3
name()

what that differs from this:

let name = 3
name

?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Before answering what () is lets get some basics defined and some examples done.

In F# a let statement has a name, zero or more arguments, and an expression.

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.

So this value

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 ...  

and this function

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 ... 

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?

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 ().

So this is a function with one argument x of type int

let c x = x + 1;;

and this is a function with one argument () of type unit

let b () = System.DateTime.Now;;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...