val cross = (for (x<-setA; y<-setB) yield (x,y)) val cross2 = (setA flatMap (x => setB map ((x,_)))
有一个更优雅的方式来做这个与交叉产品操作符,还是一些这样的?
例如:
val cross3 = setA cross setB
解决方法
import scala.collection.Set class Crossable[E1](es1: Traversable[E1]) { def ×[E2](es2: Traversable[E2]): Traversable[(E1,E2)] = for (e1 <- es1; e2 <- es2) yield (e1,e2) def cross[E2](es2: Traversable[E2]): Traversable[(E1,e2) } object Crossable { implicit def trav2Crossable[E1](es1: Traversable[E1]): Crossable[E1] = new Crossable[E1](es1) } object CrossableTest { def main(args: Array[String]): Unit = { import Crossable.trav2Crossable val es1 = Set(1,2,3) val es2 = List("a","b","c") (es1 × es2) foreach(printf(" %s%n",_)) } } % scala -cp . CrossableTest (1,c) (2,b) (3,a) (2,a) (1,a) (3,c) (1,b) (2,c)