Created
January 21, 2015 20:59
-
-
Save Jazzatola/bf4767f597c7ff7822a3 to your computer and use it in GitHub Desktop.
Tail recursive map implementation
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
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