scala 如何展平嵌套元组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13699070/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 04:45:47  来源:igfitidea点击:

How to flatten a nested tuple?

scalatuplesflatten

提问by zjffdu

I have a nested tuple structure like (String,(String,Double))and I want to transform it to (String,String,Double). I have various kinds of nested tuple, and I don't want to transform each manually. Is there any convenient way to do that?

我有一个嵌套的元组结构(String,(String,Double)),我想将它转换为(String,String,Double). 我有各种嵌套的元组,我不想手动转换每个元组。有没有什么方便的方法来做到这一点?

回答by xiefei

If you use shapeless, thisis exactly what you need, I think.

如果你用无形的是你需要什么,我想。

回答by tgr

There is no flatten on a Tupple. But if you know the structure, you can do something like this:

元组上没有展平。但是如果你知道结构,你可以做这样的事情:

implicit def flatten1[A, B, C](t: ((A, B), C)): (A, B, C) = (t._1._1, t._1._2, t._2)
implicit def flatten2[A, B, C](t: (A, (B, C))): (A, B, C) = (t._1, t._2._1, t._2._2)

This will flatten Tupple with any types. You can also add the implicit keyword to the definition. This works only for three elements. You can flatten Tupple like:

这将使任何类型的 Tupple 变平。您还可以将隐式关键字添加到定义中。这仅适用于三个元素。您可以将 Tupple 展平,例如:

(1, ("hello", 42.0))   => (1, "hello", 42.0)
(("test", 3.7f), "hi") => ("test", 3.7f, "hi")

Multiple nested Tupple cannot be flatten to the ground, because there are only three elements in the return type:

多个嵌套的 Tupple 无法平铺到地面,因为返回类型中只有三个元素:

((1, (2, 3)),4)        => (1, (2, 3), 4)

回答by arve0

Not sure about the effiency of this, but you can convert Tupleto Listwith tuple.productIterator.toList, then flattenthe nested lists:

不确定这样做的效率,但您可以转换TupleListwith tuple.productIterator.toList,然后flatten是嵌套列表:

scala> val tuple = ("top", ("nested", 42.0))
tuple: (String, (String, Double)) = (top,(nested,42.0))

scala> tuple.productIterator.map({
     |   case (item: Product) => item.productIterator.toList
     |   case (item: Any) => List(item)
     | }).toList.flatten
res0: List[Any] = List(top, nested, 42.0)