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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With