Cross product in Scala

后端 未结 7 2065
滥情空心
滥情空心 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:39

    Similar to other responses, just my approach.

    def loop(lst: List[List[Int]],acc:List[Int]): List[List[Int]] = {
      lst match {
        case head :: Nil => head.map(_ :: acc)
        case head :: tail => head.flatMap(x => loop(tail,x :: acc))
        case Nil => ???
      }
    }
    val l1 = List(10,20,30,40)
    val l2 = List(2,4,6)
    val l3 = List(3,5,7,9,11)
    
    val lst = List(l1,l2,l3)
    
    loop(lst,List.empty[Int])
    

提交回复
热议问题