The problem

P14 (*) Duplicate the elements of a list.


scala> duplicate(List('a, 'b, 'c, 'c, 'd))
res0: List[Symbol] = List('a, 'a, 'b, 'b, 'c, 'c, 'c, 'c, 'd, 'd)

Initial thoughts

Once again (see problem 12) a perfect task for flatMap() since for each element a list must be produced, but the resulting list shall be flat.


The function passed to flatMap() this time shall return a list with two elements for each element of the source list.

def duplicate[A](l:List[A]):List[A] = {
    l flatMap { e => List(e, e) }

Final considerations

This problem didn't involve new concepts, but allowed me to test again mapping and anonymous functions.


The GitHub issues page is the best place to submit corrections.