Dmitrii - 3 months ago 16

Scala Question

I have List of lists

`List[List[Int] to n]`

`Lists[Int]`

For List(List(1,2,3), List(4,5), List(6)) it would be

1*4*6, 1*5*6, 2*4*6, 2*5*6, 3*4*6, 3*5*6

and so on and return result as a List of resulting values

`List[24, 30, 48, 60, 72, 90]`

Answer

You can do it using foldLeft this way:

```
list.foldLeft(List(1)) {
case (acc, item) => acc.flatMap(v => item.map(_*v))
}
```

**Explanation**

Lets define method producing all possible multiplication of pairs of two lists:

```
def mul(a:List[Int], b:List[Int]) = b.flatMap (item => a.map(_*item))
```

this method for each item in b produces a list of items from a multiplied by current value of b

Now we can apply this procedure to all elements of list of lists, giving it initial value of List(1)