Skip to content

Instantly share code, notes, and snippets.

@tobyweston
Created January 21, 2015 20:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tobyweston/2c7075e5e3311faca5ef to your computer and use it in GitHub Desktop.
Save tobyweston/2c7075e5e3311faca5ef to your computer and use it in GitHub Desktop.
Map that!
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)
}
@Jazzatola
Copy link

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.

@Jazzatola
Copy link

@Jazzatola
Copy link

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