Scala 中的交叉产品 [英] Cross product in Scala

查看:24
本文介绍了Scala 中的交叉产品的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个二元运算符 cross(交叉乘积/笛卡尔乘积),它可以在 Scala 中使用遍历:

I want to have a binary operator cross (cross-product/cartesian product) that operates with traversables in Scala:

val x = Seq(1, 2)
val y = List('hello', 'world', 'bye')
val z = x cross y    # i can chain as many traversables e.g. x cross y cross w etc

assert z == ((1, 'hello'), (1, 'world'), (1, 'bye'), (2, 'hello'), (2, 'world'), (2, 'bye'))

仅在 Scala 中执行此操作的最佳方法是什么(即不使用 scalaz 之类的东西)?

What is the best way to do this in Scala only (i.e. not using something like scalaz)?

推荐答案

您可以使用 Scala 2.10 中的隐式类和 for-comprehension 非常简单地完成此操作:

You can do this pretty straightforwardly with an implicit class and a for-comprehension in Scala 2.10:

implicit class Crossable[X](xs: Traversable[X]) {
  def cross[Y](ys: Traversable[Y]) = for { x <- xs; y <- ys } yield (x, y)
}

val xs = Seq(1, 2)
val ys = List("hello", "world", "bye")

现在:

scala> xs cross ys
res0: Traversable[(Int, String)] = List((1,hello), (1,world), ...

这在 2.10 之前是可能的——只是不够简洁,因为您需要定义类和隐式转换方法.

This is possible before 2.10—just not quite as concise, since you'd need to define both the class and an implicit conversion method.

你也可以这样写:

scala> xs cross ys cross List('a, 'b)
res2: Traversable[((Int, String), Symbol)] = List(((1,hello),'a), ...

如果您希望 xs cross ys cross zs 返回一个 Tuple3,那么您将需要大量样板文件或像 无形.

If you want xs cross ys cross zs to return a Tuple3, however, you'll need either a lot of boilerplate or a library like Shapeless.

这篇关于Scala 中的交叉产品的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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