2015-11-02 68 views
3

我在看F#为C#开发人员书,有这个功能,我似乎无法了解什么是 F#不清楚功能的影响

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) 

为什么abctripleVariable初始化?是否因为需要在for循环中知道它们的类型(或其类型,因为它是Tuple)?定义变量abc

回答

4

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

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 

它们可以独立运行。

ab,并在forc隐藏abc环路之外定义。您可以在循环后打印ab,并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 

结果:

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

代码段使用可变阴影。变量首先被初始化为值tripleVariable(第二行),然后它们被遮蔽通过在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甚至与新的变量类型不同。

+0

学究角落:他们是* *值,不变量,除非它们被标记为“可变”。 –