gpt4 book ai didi

f# - 如何在 F# 列表和 F# 元组之间进行转换?

转载 作者:行者123 更新时间:2023-12-03 13:21:48 26 4
gpt4 key购买 nike

有什么方法可以在 F# List 和 F# Tuple 之间转换?

例如:

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

我需要两个函数来做到这一点:
let listToTuple list = ...
let tupleToList tuple = ...

先感谢您。

最佳答案

除了 listToTuple 然后 pblasucci 有正确的答案。
但是除非您对所涉及的类型类型有所了解,或者您不想进行大量装箱和拆箱,否则您不会对结果感到满意。

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# 列表和 F# 元组之间进行转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2920094/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com