user3165588
user3165588

Reputation:

F# unclear function effects

I'm reading the F# for C# developers book and there's this function that I can't seem to understand what are the effects of this function

let tripleVariable = 1, "two", "three"
let a, b, c = tripleVariable
let l = [(1,2,3); (2,3,4); (3,4,5)]
for a,b,c in l do
    printfn "triple is (%d,%d,%d)" a b c

the output is

triple is (1,2,3)
triple is (2,3,4)
triple is (3,4,5)

why a, b, c are initialized with tripleVariable? Is it because it was needed in the for loop to know their type (or its type, since it's a Tuple)?

Upvotes: 3

Views: 104

Answers (2)

Jakub Lortz
Jakub Lortz

Reputation: 14896

The code contains 2 samples. The first one is

let tripleVariable = 1, "two", "three"
let a, b, c = tripleVariable

The 2nd one

let l = [(1,2,3); (2,3,4); (3,4,5)]
for a,b,c in l do
    printfn "triple is (%d,%d,%d)" a b c

They can be run independently.

The values a, b, and c in the for loop hide the a, b, and c defined outside of the loop. You can print a, b, and c after the loop to see that they still contain the values from tripleVariable:

let tripleVariable = 1, "two", "three"
let a, b, c = tripleVariable

let l = [(1,2,3); (2,3,4); (3,4,5)]
for a,b,c in l do
    printfn "triple is (%d,%d,%d)" a b c

printfn "tripleVariable is (%A,%A,%A)" a b c

Result:

triple is (1,2,3)
triple is (2,3,4)
triple is (3,4,5)
tripleVariable is (1,"two","three")

Upvotes: 4

Tomas Petricek
Tomas Petricek

Reputation: 243051

The code snippet is using variable shadowing when defining the variables a, b and c. The variables are first initialized to the values of tripleVariable (line 2), but then they are shadowed by a new definition inside the for loop (line 4).

You can think of these as different variables - the code is equivalent to the following:

let tripleVariable = 1, "two", "three"
let a1, b1, c1 = tripleVariable
let l = [(1,2,3); (2,3,4); (3,4,5)]
for a2, b2, c2 in l do
    printfn "triple is (%d,%d,%d)" a2 b2 c2

Variable shadowing simply lets you define a variable with a name that already exists in the scope. It hides the old variable and all subsequent code will only see the new one. In the above code snippet, the old (shadowed) variables b and c even have different types than the new ones.

Upvotes: 6

Related Questions