Created
January 21, 2015 20:21
-
-
Save tobyweston/2c7075e5e3311faca5ef to your computer and use it in GitHub Desktop.
Map that!
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 maprec[B](f: A => B): List[B] = { | |
def recur(head: A, tail: List[A]): List[B] = { | |
tail match { | |
case Nil => List(f.apply(head)) | |
case _ => f.apply(head) +: recur(tail.head, tail.tail) | |
} | |
} | |
recur(elements.head, elements.tail) | |
} |
Here's a recursive implementation:
def map[A, B](as: List[A], f: A => B): List[B] = as match {
case Nil => Nil
case head :: tail => f(head) :: map(tail, f)
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
So what I remember from fpinscala is that for a tailrec version of map, you implement it using fold. You could do it all in one definition but I think to make it tailrec, the clearest way is to decompose the whole thing into separate functions.