如何在 F# 列表和 F# 元组之间进行转换? [英] How can i convert between F# List and F# Tuple?
本文介绍了如何在 F# 列表和 F# 元组之间进行转换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有某种方法可以在 F# 列表和 F# 元组之间进行转换?
Is there some way to convert between F# List and F# Tuple?
例如:
[1;2;3] -> (1,2,3)
(1,2,3,4) -> [1;2;3;4]
我需要两个函数来做到这一点:
I need two Functions to do that:
let listToTuple list = ...
let tupleToList tuple = ...
提前致谢.
推荐答案
除了 listToTuple 之外,pblasucci 还有正确的答案.但是除非您对所涉及的类型类型有所了解,或者不想进行大量装箱和拆箱操作,否则您不会对结果感到满意.
Besides listToTuple then pblasucci has the right answer. But you wont be happy with the result unless you know something about type types involved, or if you wan't to do a lot of boxing and unboxing.
let tupleToList t =
if Microsoft.FSharp.Reflection.FSharpType.IsTuple(t.GetType())
then Some (Microsoft.FSharp.Reflection.FSharpValue.GetTupleFields t |> Array.toList)
else None
let listToTuple l =
let l' = List.toArray l
let types = l' |> Array.map (fun o -> o.GetType())
let tupleType = Microsoft.FSharp.Reflection.FSharpType.MakeTupleType types
Microsoft.FSharp.Reflection.FSharpValue.MakeTuple (l' , tupleType)
这篇关于如何在 F# 列表和 F# 元组之间进行转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文