99 Scala Problems 14 - Duplicate the elements of a list
By Leonardo Giordani - Updated on
The problem¶
P14 (*) Duplicate the elements of a list.
Example:
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.
Solution¶
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.
Feedback¶
The GitHub issues page is the best place to submit corrections.
Part 14 of the 99 Scala Problems series
Previous articles
- 99 Scala Problems 01 - Find the last element of a list
- 99 Scala Problems 02 - Find the last but one element of a list
- 99 Scala Problems 03 - Find the Kth element of a list
- 99 Scala Problems 04 - Find the number of elements of a list
- 99 Scala Problems 05 - Reverse a list
- 99 Scala Problems 06 - Find out whether a list is a palindrome
- 99 Scala Problems 07 - Flatten a nested list structure
- 99 Scala Problems 08 - Eliminate consecutive duplicates of list elements
- 99 Scala Problems 09 - Pack consecutive duplicates of list elements into sublists
- 99 Scala Problems 10 - Run-length encoding of a list.
- 99 Scala Problems 11 - Modified run-length encoding
- 99 Scala Problems 12 - Decode a run-length encoded list
- 99 Scala Problems 13 - Run-length encoding of a list (direct solution)