开发者

Cross product of 2 sets in Scala

开发者 https://www.devze.com 2022-12-28 04:30 出处:网络
val cross = (for (x<-setA; y<-setB) yield (x,y)) val cross2 = (setA flatMap (x => setB map ((x,_)))
val cross = (for (x<-setA; y<-setB) yield (x,y))

val cross2 = (setA flatMap (x => setB map ((x,_)))

开发者_如何学运维Is there a more elegant way to do this with a cross product operator, or some such? E.g:

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)] =
      for (e1 <- es1; e2 <- es2) yield (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,b)
  (3,c)
  (1,b)
  (2,c)
0

精彩评论

暂无评论...
验证码 换一张
取 消