99 Scala Problems 15 - Duplicate the elements of a list a given number of times
By Leonardo Giordani - Updated on
The problem¶
P15 (**) Duplicate the elements of a list a given number of times.
Example:
scala> duplicateN(3, List('a, 'b, 'c, 'c, 'd))
res0: List[Symbol] = List('a, 'a, 'a, 'b, 'b, 'b, 'c, 'c, 'c, 'c, 'c, 'c, 'd, 'd, 'd)
Initial thoughts¶
Problem 12 already taught me to use fill()
to build lists of repeated elements so this could be a good occasion to use it again.
Solution¶
This problem is a generalization of the previous problem 14 which required to duplicate the elements of a list. There we could build the list into an anonymous function with the List(e, e)
syntax.
For this problem we have to use a more general solution, which is the fill()
method of the List
object (not class), already discovered in problem 12. This method is expressed in a curried form, thus the two argument applications.
Again, since the result of fill()
is a list, we have to flatten it through flatMap()
.
def duplicateN[A](n: Int, l: List[A]):List[A] = {
l flatMap { e => List.fill(n)(e) }
}
Scala allows us to express the anonymous function in a shorter way, making use of the underscore wild card.
def duplicateN2[A](n: Int, l: List[A]):List[A] = {
l flatMap { List.fill(n)(_) }
}
Final considerations¶
Previous problems gave me all I needed to solve this one. I used anonymous functions and mapping, which are a very important component of Scala. I learned how to simplify an anonymous function using the underscore.
Feedback¶
The GitHub issues page is the best place to submit corrections.
Part 15 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)
- 99 Scala Problems 14 - Duplicate the elements of a list