Scala FlatMap scenario


#1

Let XYZ is a program which takes integer input from command line.
Below is the list of oparation that needs to be achived:

  1. A list must be generated with the input number of elements in the list starting from one i.e when input is 3 List(1,2,3) must be generated.
  2. Each number in the List generated i.e numberList = List(1,2,3) must be used to create seperate lists with elements equal to the number starting from 1, i.e when input is 3; List(1), List(1, 2), List(1,2,3) must be created and joined together to give output resultList as List(1, 1, 2, 1, 2, 3).
    So how can I achive this using FlatMap??

#2

What you are describing is exactly what flatMap does:

def mkList(i: Int) = List.range(1, i + 1)

mkList(3).flatMap(mkList) // List(1, 1, 2, 1, 2, 3)