Cross product in Scala

后端 未结 7 2061
滥情空心
滥情空心 2020-12-01 09:04

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 = Lis         


        
7条回答
  •  无人及你
    2020-12-01 09:33

    Here is the implementation of recursive cross product of arbitrary number of lists:

    def crossJoin[T](list: Traversable[Traversable[T]]): Traversable[Traversable[T]] =
      list match {
        case xs :: Nil => xs map (Traversable(_))
        case x :: xs => for {
          i <- x
          j <- crossJoin(xs)
        } yield Traversable(i) ++ j
      }
    
    crossJoin(
      List(
        List(3, "b"),
        List(1, 8),
        List(0, "f", 4.3)
      )
    )
    
    res0: Traversable[Traversable[Any]] = List(List(3, 1, 0), List(3, 1, f), List(3, 1, 4.3), List(3, 8, 0), List(3, 8, f), List(3, 8, 4.3), List(b, 1, 0), List(b, 1, f), List(b, 1, 4.3), List(b, 8, 0), List(b, 8, f), List(b, 8, 4.3))
    

提交回复
热议问题