Created
September 8, 2019 12:05
-
-
Save kmizu/36b8d054954f60a3338415d13b88c076 to your computer and use it in GitHub Desktop.
Pure `map` method using destructive operations
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
def map[A, B](xs: List[A])(f: A => B): List[B] = { | |
var ys = xs | |
val result = collection.mutable.Buffer.empty[B] | |
while(ys != Nil) { | |
result += f(ys.head) | |
ys = ys.tail | |
} | |
result.toList | |
} | |
println(map(List(1, 2, 3))(x => x + 1)) // List(2, 3, 4) | |
println(map(List(1, 2, 3))(x => x * x)) // List(1, 4, 9) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment