How can i convert between F# List and F# Tuple?

前端 未结 5 1010
Happy的楠姐
Happy的楠姐 2020-11-30 10:45

Is there some way to convert between F# List and F# Tuple?

For example:

[1;2;3] -> (1,2,3)    
(1,2,3,4) -> [1;2;3;4]

I need

5条回答
  •  星月不相逢
    2020-11-30 11:25

    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)
    

提交回复
热议问题