-1

I've got

val l List[List[Int]] = List(List(0,0,0),List(1,1,1))

and I want to get it zipped. Is there any succinct way to do it instead of accessing each element of main list by index and zip it together with zip command?

ahajib
  • 12,838
  • 29
  • 79
  • 120
Dmitrii
  • 604
  • 2
  • 9
  • 30
  • Could you show us the output you're expecting? – Zoltán Jul 12 '16 at 14:12
  • What if there are more than 22 elements in the list (you can only have up to 22 elements in a tuple)? What if there is only one (or none at all)? What if lists have different lengths? Or do you mean by "zip" something completely different than what the rest of us thinks? – Dima Jul 12 '16 at 14:13

1 Answers1

3

This works, under the assumption that the outer list has exacly two inner lists.

List(List(0,0,0), List(1, 1, 1)) match {
  case l1 :: l2 :: Nil => l1 zip l2
  case x => ??? // up to you
}

In order to take into account the possibility of failure, you can wrap the result into an Option.

val x = List(List(0,0,0), List(1, 1, 1))
val res: Option[List[Int]] = x match {
  case l1 :: l2 :: Nil => Some(l1 zip l2)
  case x => None
}
Gabriele Petronella
  • 106,943
  • 21
  • 217
  • 235