如何压扁嵌套元组?

时间:2012-12-04 08:51:53

标签: scala tuples flatten

我有一个像(String,(String,Double))这样的嵌套元组结构,我想把它转换为(String,String,Double)。我有各种嵌套元组,我不想手动转换每个元组。有没有方便的方法呢?

5 个答案:

答案 0 :(得分:23)

如果您使用shapeless,我认为this正是您所需要的。

答案 1 :(得分:7)

Tupple上没有展平。但是如果你知道结构,你可以这样做:

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)

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

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

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

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

答案 2 :(得分:1)

不确定这是否有效,但您可以使用TupleList转换为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)

答案 3 :(得分:1)

answer above

粘贴此实用程序代码:

import shapeless._
import ops.tuple.FlatMapper
import syntax.std.tuple._
trait LowPriorityFlatten extends Poly1 {
  implicit def default[T] = at[T](Tuple1(_))
}
object flatten extends LowPriorityFlatten {
  implicit def caseTuple[P <: Product](implicit lfm: Lazy[FlatMapper[P, flatten.type]]) =
    at[P](lfm.value(_))
}

然后您就可以展平任何嵌套的元组:

scala> val a = flatten(((1,2),((3,4),(5,(6,(7,8))))))
a: (Int, Int, Int, Int, Int, Int, Int, Int) = (1,2,3,4,5,6,7,8)

<块引用>

请注意,此解决方案不适用于自定义 case class 类型,该类型将在输出中转换为 String

scala> val b = flatten(((Cat("c"), Dog("d")), Cat("c")))
b: (String, String, String) = (c,d,c)

答案 4 :(得分:0)

在我看来,简单的模式匹配是可行的

scala> val motto = (("dog", "food"), "tastes good")
val motto: ((String, String), String) = ((dog,food),tastes good)

scala> motto match {
     | case ((it, really), does) => (it, really, does)
     | }
val res0: (String, String, String) = (dog,food,tastes good)

或者如果你有一个这样的元组的集合:

scala> val motto = List(
     | (("dog", "food"), "tastes good")) :+ (("cat", "food"), "tastes bad")
val motto: List[((String, String), String)] = List(((dog,food),tastes good), ((cat,food),tastes bad))

scala> motto.map {
     | case ((one, two), three) => (one, two, three)
     | }
val res2: List[(String, String, String)] = List((dog,food,tastes good), (cat,food,tastes bad))

我觉得即使你有几个案例也会很方便。