本文介绍了F#扁平化嵌套元组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以在不显式映射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#扁平化嵌套元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!