Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
682 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 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...