49

在 F# 代码中,我有一个元组:

let myWife=("Tijana",32)

我想分别访问元组的每个成员。例如,这是我想通过 I can't 实现的

Console.WriteLine("My wife is {0} and her age is {1}",myWife[0],myWife[1])

这段代码显然不起作用,我认为您可以收集我想要实现的目标。

4

4 回答 4

90

你想通过让她的年龄不可变来防止你的妻子变老吗?:)

对于只包含两个成员的元组,您可以fst提取snd对的成员。

let wifeName = fst myWife;
let wifeAge = snd myWife;

对于更长的元组,您必须将元组解包到其他变量中。例如,

let _, age = myWife;;
let name, age = myWife;;
于 2009-03-01T18:33:43.330 回答
24

另一个非常有用的事情是模式匹配(就像使用“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)
于 2009-03-01T22:05:08.457 回答
17

您可以使用函数 fst 获取第一个元素,使用 snd 获取第二个元素。您还可以编写自己的“第三个”函数:

let third (_, _, c) = c

在此处阅读更多内容:F# 语言参考,元组

于 2010-07-16T14:32:57.553 回答
8

您还可以编写一定长度的解包函数:

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) 
于 2017-01-30T08:58:08.377 回答