How can I refer to a specific member of a Tuple of any size in F#

前端 未结 4 1001
囚心锁ツ
囚心锁ツ 2020-12-11 23:54

okay, this might be a silly question.

So I have some tuples of size 4 so like (int,int,int,int)

If it were a 2 tuple I could use fst(myTuple) to refer to th

4条回答
  •  一个人的身影
    2020-12-12 00:22

    For the sheer novelty, here's an overloaded operator that works for tuples of any* size.

    let (@) t idx =
        match t.GetType().GetProperty(sprintf "Item%d" idx) with
        | null -> invalidArg "idx" "invalid index"
        | p -> p.GetValue(t, null) |> unbox
    
    //Usage
    let t = 4, 5, 6
    let n1 : int = t@1 //4
    let i = 2
    let n2 = t@i //5
    

    * Any, in this context, has a more limited meaning, specifically, up to 7.

提交回复
热议问题