Question

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?

Was it helpful?

Solution

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))

OTHER TIPS

x.flatMap(i => l.map(i::_))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top