flatMap on a sequence of tuples

2019-09-14 10:23发布

问题:

Given the following code :

def flatMap2[A, B, C](s:Seq[(A, B)])(f: B => Seq[C]) : Seq[(A, C)] =
  s.flatMap { case (a, b) => f(b).map((a, _)) }

Is there a better way to code that (maybe something exit in scalaz) ?

Can you help me to find a better name ?

Is there a more generic abstraction to use (Iterable, TraversableOnce) ?

回答1:

How about this:

import scala.collection.GenTraversable
import scala.collection.GenTraversableLike
import scala.collection.GenTraversableOnce
import scala.collection.generic.CanBuildFrom

implicit class WithMapFlatMapValues[A, B, Repr <: GenTraversable[(A, B)]](val self: GenTraversableLike[(A, B), Repr]) extends AnyVal {
  def flatMapValues[C, That](f: B => GenTraversableOnce[C])(implicit bf: CanBuildFrom[Repr, (A, C), That]) = {
    self.flatMap { case (a, b) => f(b).toIterator.map(a -> _) } 
  }
}

So you can do:

Vector("a"->1, "b"->2).flatMapValues(Seq.fill(_)("x"))
// res1: Vector[(String, String)] = Vector((a,x), (b,x), (b,x))

Set("a"->1, "b"->2).flatMapValues(Iterator.tabulate(_)(_+"x"))
// res2: Set[(String, String)] = Set((a,0x), (b,0x), (b,1x))

And you can do it with Iterator too (so you have all of TraversableOnce covered):

implicit class WithMapFlatMapValuesItr[A, B](val self: Iterator[(A, B)]) extends AnyVal {
  def flatMapValues[C](f: B => GenTraversableOnce[C]) = {
    for { (a, b) <- self; c <- f(b).toIterator } yield (a -> c)
  }
}

val i1 = Iterator("a"->1, "b"->2).flatMapValues(Seq.fill(_)("x"))
// i1: Iterator[(String, String)] = non-empty iterator
i1.toVector
// res6: Vector[(String, String)] = Vector((a,x), (b,x), (b,x))


回答2:

Looks little better:

def flatMap2[A, B, C](List[(A, B)])(f: B => Seq[C]) : List[(A, C)] =
   for((a,b) <- s; bb <- f(b)) yield a -> bb

But things you're trying to do here is more like about multi-map (with preserving order) than just sequence of tuples:

def flatMap2[A, B, C](s: ListMap[A, List[B]])(f: B => List[C]) : Map[A, List[C]] = 
   s.mapValues(_.flatMap(f))

scala> flatMap2(ListMap(2 -> List("a"), 1 -> List("c")))(x => List(x + "a"))
res4: scala.collection.immutable.Map[Int,List[String]] = Map(2 -> List(aa), 1 -> List(ca))

ListMap saves original order here. mapValues returns view on ListMap, which also will preserve the order.

Scalaz's monoids could help you with adding elelements to such Map:

yourListMap |+| ListMap(key -> List(value))

scala>  val map = ListMap(2 -> List("a"), 1 -> List("c"))
map: scala.collection.immutable.ListMap[Int,List[String]] = Map(2 -> List(a), 1 -> List(c))

scala> (map: Map[Int,List[String]]) |+| ListMap(1 -> List("b"))
res11: scala.collection.immutable.Map[Int,List[String]] = Map(2 -> List(a), 1 -> List(c, b))

You can use Seq instead of List, but then you won't have implicit conversion to the semigroup.



回答3:

The question may be unclear, at this point I would say:

// s1: Seq[(A, B)], f: B => C
val s2: Seq[(A, C)] = s1.map((a, b) => a -> f(b))