F# flatten nested tuples

后端 未结 1 599
孤独总比滥情好
孤独总比滥情好 2021-01-18 06:42

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))

1条回答
  •  囚心锁ツ
    2021-01-18 07:13

    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
    

    So, for example:

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

    Will give you:

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

    NOTE: This answer is based on code found here.

    0 讨论(0)
提交回复
热议问题