有没有办法在F#中展平任意大小的元组而不显式映射它们?
(fun ((((a0,a1),a2),b),c) -> (a0,a1,a2,b,c))
作为一个注释,我从FParsec获得了这些元组,但如果它通常可用,那么这个功能会很方便。
感谢,
答案 0 :(得分:3)
你不能轻易做到,但有一点反思就有可能:
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]
注意:此答案基于找到的代码lifecycle-mapping plugin。