Scala中对的惯用扁平化

时间:2013-09-18 13:27:40

标签: scala

我有一个函数将类型A的值映射到一对(Seq [B],Seq [C])。我想将函数应用于A的序列,并返回一对展平的Seq [B]和Seq [C]。以下是代码段:

val a: Seq[A] 
val mapped: Seq[(Seq[B], Seq[C])] = a.map(f)

val (b, c) = mapped.unzip
val bc: (Seq[B], Seq[C]) = (b.flatten, c.flatten)

解决方案是可以接受的,但是有更惯用的方法吗?我虽然关于for-comprehensions或flatMaps,但我看不出如何将它们应用于这对。

3 个答案:

答案 0 :(得分:3)

shapeless 2.0.0-M1 is available,您可map on tuples

import shapeless._, syntax.std.tuple._, poly._

val l = Seq(Seq(1, 2, 3, 4, 5) -> Seq('a, 'b, 'c), Seq(101, 102, 103) -> Seq('d, 'e, 'f))

type SS[T] = Seq[Seq[T]]
object flatten extends (SS ~> Seq) {
  def apply[T](ss: SS[T]) = ss.flatten
}

l.unzip.map(flatten) // l.unzip.hlisted.map(flatten).tupled for older versions of shapeless
// (Seq[Int], Seq[Symbol]) = (List(1, 2, 3, 4, 5, 101, 102, 103),List('a, 'b, 'c, 'd, 'e, 'f))

实际上应该可以convert多态方法自动生成多态函数,但是这段代码不起作用:

def flatten[T](s: Seq[Seq[T]]) = s.flatten
l.unzip.map(flatten _)
//<console>:31: error: type mismatch;
// found   : Seq[T]
// required: Seq[Seq[T]]
//              l.unzip.map(flatten _)
//                          ^

答案 1 :(得分:3)

我可能会将Monoid instance用于Tuple2,将Foldable实例用于List(通过其Traverse发挥作用instancesum结果列表。

scala> import scalaz._, Scalaz._
import scalaz._
import Scalaz._

scala> val a = List(11,222,3333,44444,555555)
a: List[Int] = List(11, 222, 3333, 44444, 555555)

scala> def f(a: Int): (List[String], List[Int]) = (a.toString.tails.toList, a.toString.tails.toList.map(_.size))
f: (a: Int)(List[String], List[Int])

scala> val mapped = a map f
mapped: List[(List[String], List[Int])] = List((List(11, 1, ""),List(2, 1, 0)), (List(222, 22, 2, ""),List(3, 2, 1, 0)), (List(3333, 333, 33, 3, ""),List(4, 3, 2, 1, 0)), (List(44444, 4444, 444, 44, 4, ""),List(5, 4, 3, 2, 1, 0)), (List(555555, 55555, 5555, 555, 55, 5, ""),List(6, 5, 4, 3, 2, 1, 0)))

scala> mapped.suml
res1: (List[String], List[Int]) = (List(11, 1, "", 222, 22, 2, "", 3333, 333, 33, 3, "", 44444, 4444, 444, 44, 4, "", 555555, 55555, 5555, 555, 55, 5, ""),List(2, 1, 0, 3, 2, 1, 0, 4, 3, 2, 1, 0, 5, 4, 3, 2, 1, 0, 6, 5, 4, 3, 2, 1, 0))

UPD:如果你真的想要Seq,这就是你需要在范围内使它工作的地方:

implicit val isoTraverse: IsomorphismTraverse[Seq, List] = new IsomorphismTraverse[Seq, List] {
  def G = Traverse[List]
  def iso = new IsoFunctorTemplate[Seq, List] {
    def to[A](sa: Seq[A]): List[A] = sa.toList
    def from[A](la: List[A]): Seq[A] = la.toSeq
  }
}

答案 2 :(得分:1)

我发现你的代码并不特别是非惯用语,但这就是我写的内容。请注意,我不相信我的代码比你的更好,我只是折叠的粉丝。

// For testing purposes only, replace with your own code.
val b = List((List(1, 2), List(5, 6)), (List(3, 4), List(7, 8)))

val (l, r) = b.foldLeft((List[Int](), List[Int]())) {(acc, a) =>
  (acc._1 ::: a._1, acc._2 ::: a._2)
}

// Prints 'List(1, 2, 3, 4)'
println(l)

// Prints 'List(5, 6, 7, 8)'
println(r)