F#功能效果不明

时间:2015-11-02 16:45:37

标签: f#

我正在阅读 F#for C#developers book,这个函数我似乎无法理解这个函数有什么影响

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

输出是

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

为什么abc已使用tripleVariable进行初始化?是因为在for循环中需要知道它们的类型(或类型,因为它是Tuple)?

2 个答案:

答案 0 :(得分:6)

在定义变量abc时,代码段正在使用变量阴影。首先将变量初始化为tripleVariable(第2行)的值,然后通过for循环(第4行)中的新定义阴影

您可以将这些视为不同的变量 - 代码等同于以下内容:

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

变量阴影只是让您定义一个名称已在作用域中存在的变量。它隐藏了旧变量,所有后续代码只会看到新变量。在上面的代码段中,旧(阴影)变量bc甚至具有与新变量不同的类型。

答案 1 :(得分:4)

代码包含 2 样本。第一个是

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

它们可以独立运行。

a循环中的值bcfor会隐藏ab和{{1}在循环之外定义。您可以在循环后打印cab,看看它们是否仍然包含来自c的值:

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