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

let myWife=("Tijana",32)

我想分别访问元组的每个成员。例如,我想要实现的目标不能

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)

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

let third (_, _, c) = c

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

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

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) 
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top