好吧,这可能是一个愚蠢的问题.
所以我有一些大小为4的元组,因此(int,int,int,int)
如果它是2元组,我可以使用fst(myTuple)来引用第一个元素.我怎么能说,参考4元组的第三个元素?
使用模式匹配:
let tup = 1, 2, 3, 4
let _,_,third,_ = tup
printfn "%d" third // displays "3"
Run Code Online (Sandbox Code Playgroud)
这在元组的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
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1077 次 |
最近记录: |