F # let expression semantics with comma

I am learning F #. I started by looking at F # samples from Microsoft.

I came across this statement:

let line1,line2 = 
    use sr = System.IO.File.OpenText @"test.txt"
    let line1 = sr.ReadLine() 
    let line2 = sr.ReadLine() 
    (line1,line2)

      

Can anyone explain this expression to me?

What type is defined here? Function? Tuple?

Why line1

and line2

should be overridden in the definition line1,line2

( let line1 =

... let line2 =

)?

What's with the last line, (line1, line2)

and how does it relate to the type of the original definition? Does the function return?

Is "expression" even the right word to define in F #?

Thanks.

+3


a source to share


1 answer


The general view for binding id values ​​in F # is

let pattern = expression

      

In this case, the template is "line1, line2", which is a collection of tuples, it will wait to bind to 2-tuples of values ​​and names these two values ​​"line1" and "line2".



The expression is the next 4 lines. There are local variables inside this expression. They are also named "line1" and "line2", but they could easily have been renamed "x" and "y" or whatever - the scope of these identifiers is local to this indented expression. (The fact that the same names are used as names in the outer scope does not affect the compiler.)

The final string if expression is the "return value" of the expression. In this case, it returns a 2-tuple of "line1" and "line2" values ​​(or "x" and "y" if you rename them for clarity). By the way, since these two values ​​are of type "string", the return type is "string * string", which is a 2-tuple, where each value is a string. This means that the original names "line1" and "line2" on the first line will be defined as "string".

F # is functional, and so in some sense "everything is an expression" and "no statements" (only sequences of expressions that are evaluated sequentially), but that's okay. IMO (ab) uses the term "operator" to describe the inner strings of "let" unless you're trying to be very precise.

+12


a source







All Articles