F# 展平嵌套的元组 [英] F# flatten nested tuples

查看:29
本文介绍了F# 展平嵌套的元组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在 F# 中展平任意大小的元组,而无需显式映射它们?

is there a way to flatten tuples of arbitrary size in F# without explicitly mapping them?

(fun ((((a0,a1),a2),b),c) ->  (a0,a1,a2,b,c))

请注意,我从 FParsec 获取这些类型的元组,但如果它普遍可用,该功能会很方便.

As a note I'm getting these kind of tuples from FParsec but the capability would be convenient if it was available generally.

谢谢,

推荐答案

你不能轻易做到,但稍加反思是可能的:

You can't do it easily, but with a bit of reflection it is possible:

let isTuple tuple =
    Microsoft.FSharp.Reflection.FSharpType.IsTuple(tuple.GetType()) 

let tupleValues (tuple : obj) = 
    Microsoft.FSharp.Reflection.FSharpValue.GetTupleFields tuple |> Array.toList

let rec flatten tupleFields =
    tupleFields |> List.collect(fun value ->
        match isTuple value with
        | true -> flatten (tupleValues value)
        | false -> [value]
    )

let tupleToList (tuple : obj) = 
    if isTuple tuple
        then Some (tupleValues tuple |> flatten)
        else None

例如:

let s = tupleToList ((100,101,102,103),1,2,3,(4,5))

会给你:

[100; 101; 102; 103; 1; 2; 3; 4; 5]

注意:此答案基于找到的代码 这里.

NOTE: This answer is based on code found here.

这篇关于F# 展平嵌套的元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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