Skip to content

Instantly share code, notes, and snippets.

@Jazzatola
Created January 21, 2015 20:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Jazzatola/bf4767f597c7ff7822a3 to your computer and use it in GitHub Desktop.
Save Jazzatola/bf4767f597c7ff7822a3 to your computer and use it in GitHub Desktop.
Tail recursive map implementation
package org.example
import scala.annotation.tailrec
object Mapper {
@tailrec
def foldLeft[A, B](as: List[A], z: B)(f: (B, A) => B): B = as match {
case Nil => z
case a :: as => foldLeft(as, f(z, a))(f)
}
def reverse[A](as: List[A]): List[A] =
foldLeft(as, List[A]())((z, a) => a :: z)
def foldRight[A, B](as: List[A], z: B)(f: (A, B) => B): B =
foldLeft(reverse(as), z)((z, a) => f(a, z))
def map[A, B](as: List[A], f: A => B): List[B] =
foldRight(as, Nil:List[B])((a, z) => f(a) :: z)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment