Created
March 1, 2012 19:37
-
-
Save dholbrook/1952521 to your computer and use it in GitHub Desktop.
S99 P15
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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