Skip to content

Instantly share code, notes, and snippets.

@dholbrook
Created March 1, 2012 19:37
Show Gist options
  • Save dholbrook/1952521 to your computer and use it in GitHub Desktop.
Save dholbrook/1952521 to your computer and use it in GitHub Desktop.
S99 P15
/*
* S99 P15 http://aperiodic.net/phil/scala/s-99/
* (**) 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)
*/
object S9915 extends App {
//with flatmap
def duplicateN[A](n: Int, l: List[A]): List[A] = l flatMap { List.fill(n)(_) }
val r = duplicateN(3, List('a, 'b, 'c, 'c, 'd))
assert(r == List('a, 'a, 'a, 'b, 'b, 'b, 'c, 'c, 'c, 'c, 'c, 'c, 'd, 'd, 'd))
//--------------------------------
//flatmap is map + flatten
def duplicateN2[A](n: Int, l: List[A]): List[A] = {
val ll: List[List[A]] = l.map({ i: A => List.fill(n)(i) })
ll.flatten
}
val r2 = duplicateN2(3, List('a, 'b, 'c, 'c, 'd))
assert(r2 == List('a, 'a, 'a, 'b, 'b, 'b, 'c, 'c, 'c, 'c, 'c, 'c, 'd, 'd, 'd))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment