0

I am new to scala and want to get the following thing done using map, flatMap, and/or for comprehension.

I have a list of lists l = List[List[T]]. For example, l = [[1,2,3],[2,4,6,4],[3,4,6,2,3]]. Note that each list inside l can have varying length.

Now I have val x: List[Int] = [1,2,3] and I want to do some operation on x and l that returns [[1,1,2,3], [1,2,4,6,4], [1,3,4,6,2,3], [2,1,2,3], [2,2,4,6,4], [2,3,4,6,2,3], [3,1,2,3], [3,2,4,6,4], [3,3,4,6,2,3]] (the order of sublists doesn't matter).

I feel like I should use map or flatMap or for-loop to do this but after a long time of trial I can't even get the type correct. Can anyone help me on it?

zyl1024
  • 690
  • 1
  • 9
  • 23
  • Brackets are generally understood to be lists but if that is your actual Scala code then you'll want to use `List()` as shown in my answer. The type for your example would be `List[Int](1,2,3)` or just let the types be inferred and use `val x = List(1,2,3)`. – Brian Jun 04 '14 at 18:08

2 Answers2

2
x.flatMap(i => l.map(i::_))
Lee
  • 142,018
  • 20
  • 234
  • 287
2
scala> val ls = List(List(1,2,3),List(2,4,6,4),List(3,4,6,2,3))
ls: List[List[Int]] = List(List(1, 2, 3), List(2, 4, 6, 4), List(3, 4, 6, 2, 3))

scala> val xs: List[Int] = List(1,2,3)
xs: List[Int] = List(1, 2, 3)

scala> for(x <- xs; l <- ls) yield x +: l
res22: List[List[Int]] = List(List(1, 1, 2, 3), List(1, 2, 4, 6, 4), List(1, 3, 4, 6, 2, 3), List(2, 1, 2, 3), List(2, 2, 4, 6, 4), List(2, 3, 4, 6, 2, 3), List(3, 1, 2, 3), List(3, 2, 4, 6, 4), List(3, 3, 4, 6, 2, 3))
Brian
  • 20,195
  • 6
  • 34
  • 55