Scala - can yield be used multiple times with a for loop?

前端 未结 6 2197
-上瘾入骨i
-上瘾入骨i 2020-12-10 11:56

An example:

val l = List(1,2,3)
val t = List(-1,-2,-3)

Can I do something like this?

for (i <- 0 to 10) yield (l(i)) yie         


        
6条回答
  •  难免孤独
    2020-12-10 12:16

    Here is a type-agnostic solution for an unknown, varying number of elements in a unknown number of lists:

    def xproduct (xx: List [List[_]]) : List [List[_]] = 
      xx match {
        case aa :: bb :: Nil => 
          aa.map (a => bb.map (b => List (a, b))).flatten       
        case aa :: bb :: cc => 
          xproduct (bb :: cc).map (li => aa.map (a => a :: li)).flatten
        case _ => xx
    }
    

    For 2 Lists it is overengineered. You could although call it

       xproduct (List (l, t))
    

提交回复
热议问题