Skip to content

Instantly share code, notes, and snippets.

@kmizu
Created September 8, 2019 12:05
Show Gist options
  • Save kmizu/36b8d054954f60a3338415d13b88c076 to your computer and use it in GitHub Desktop.
Save kmizu/36b8d054954f60a3338415d13b88c076 to your computer and use it in GitHub Desktop.
Pure `map` method using destructive operations
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