[英]How can I refer to a specific member of a Tuple of any size in F#
好吧,這可能是一個愚蠢的問題。
所以我有一些大小為4的元組,因此(int,int,int,int)
如果它是2元組,我可以使用fst(myTuple)來引用第一個元素。 我怎么能說,參考4元組的第三個元素?
使用模式匹配:
let tup = 1, 2, 3, 4
let _,_,third,_ = tup
printfn "%d" third // displays "3"
這在元組的MSDN文檔中直接描述: 元組(F#)
這是@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
對於純粹的新穎性,這里是一個重載的運算符,適用於任何*大小的元組。
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
*在這種情況下,任何具有更有限的含義,特別是最多7個。
如果你想隨機訪問一般大小的元組,那么這是不可能的。 對於任何給定的大小,您可以按照ildjarn的答案(將其擴展為四,五等),但它是唯一(功能)方式。
一般來說,元組的一種可能性是首先將它轉換為列表,如此處所示 ,但這並不是太漂亮,因為它需要反射。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.