如何在F#中引用任何大小的元组的特定成员

jef*_*eff 3 syntax f# tuples

好吧,这可能是一个愚蠢的问题.

所以我有一些大小为4的元组,因此(int,int,int,int)

如果它是2元组,我可以使用fst(myTuple)来引用第一个元素.我怎么能说,参考4元组的第三个元素?

ild*_*arn 8

使用模式匹配:

let tup = 1, 2, 3, 4
let _,_,third,_ = tup
printfn "%d" third // displays "3"
Run Code Online (Sandbox Code Playgroud)

这在元组的MSDN文档中直接描述:元组(F#)

  • @Daniel:我不相信这些属性可以在F#中访问而不使用反射或装箱然后向下转换到适当的`System.Tuple <T1,T2,...,Tn>`类型. (4认同)
  • @Daniel - 我认为F#隐藏了它们,因为它支持无限长度的元组:.NET元组只能达到8.在引擎盖下,F#将元组嵌套在第8位以表示长元组. (2认同)

Ste*_*sen 5

这是 @Daniels 新颖解决方案的一个版本,它计算Rest底层元组表示的偏移量,以支持对任意长元组的基于位置的访问。错误处理省略。

let (@) t idx =
    let numberOfRests = (idx - 1) / 7
    let finalIdx = idx - 7 * numberOfRests
    let finalTuple =
        let rec loop curTuple curRest =
            if curRest = numberOfRests then curTuple
            else loop (curTuple.GetType().GetProperty("Rest").GetValue(curTuple, null)) (curRest+1)
        loop t 0

    finalTuple
     .GetType()
     .GetProperty(sprintf "Item%d" finalIdx)
     .GetValue(finalTuple, null) 
     |> unbox

//fsi usage:
> let i : int = (1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36)@36;;

val i : int = 36
Run Code Online (Sandbox Code Playgroud)