在 F# 代码中,我有一个元组:
let myWife=("Tijana",32)
我想分别访问元组的每个成员。例如,这是我想通过 I can't 实现的
Console.WriteLine("My wife is {0} and her age is {1}",myWife[0],myWife[1])
这段代码显然不起作用,我认为您可以收集我想要实现的目标。
你想通过让她的年龄不可变来防止你的妻子变老吗?:)
对于只包含两个成员的元组,您可以fst
提取snd
对的成员。
let wifeName = fst myWife;
let wifeAge = snd myWife;
对于更长的元组,您必须将元组解包到其他变量中。例如,
let _, age = myWife;;
let name, age = myWife;;
另一个非常有用的事情是模式匹配(就像使用“let”绑定提取元素时一样)可以在其他情况下使用,例如在编写函数时:
let writePerson1 person =
let name, age = person
printfn "name = %s, age = %d" name age
// instead of deconstructing the tuple using 'let',
// we can do it in the declaration of parameters
let writePerson2 (name, age) =
printfn "name = %s, age = %d" name age
// in both cases, the call is the same
writePerson1 ("Joe", 20)
writePerson2 ("Joe", 20)
您还可以编写一定长度的解包函数:
let unpack4 tup4 ind =
match ind, tup4 with
| 0, (a,_,_,_) -> a
| 1, (_,b,_,_) -> b
| 2, (_,_,c,_) -> c
| 3, (_,_,_,d) -> d
| _, _ -> failwith (sprintf "Trying to access item %i of tuple with 4 entries." ind)
或者
let unpack4 tup4 ind =
let (a, b, c, d) = tup4
match ind with
| 0 -> a
| 1 -> b
| 2 -> c
| 3 -> d
| _ -> failwith (sprintf "Trying to access item %i of tuple with 4 entries." ind)