如何在F#列表和F#元组之间转换? [英] How can i convert between F# List and F# Tuple?

查看:137
本文介绍了如何在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆