flatMap在元组序列上 [英] flatMap on a sequence of tuples

查看:495
本文介绍了flatMap在元组序列上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定以下代码:

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, _)) }

可以帮我找到一个更好的名字吗?

Can you help me to find a better name ?

有一个更通用的抽象使用( Iterable TraversableOnce )?

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

推荐答案

如何:

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 -> _) } 
  }
}

所以你可以这样做:

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))

你也可以用Iterator来做(所以你覆盖了所有的TraversableOnce):

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))

这篇关于flatMap在元组序列上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆