Skip to content

Instantly share code, notes, and snippets.

@nicerobot
Created September 8, 2015 02:01
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 nicerobot/6213be207dd87b2d5e75 to your computer and use it in GitHub Desktop.
Save nicerobot/6213be207dd87b2d5e75 to your computer and use it in GitHub Desktop.
map vs flatMap
// flatMap is basically just building a List by appending Lists:
// List(1) ++ List(2) ++ List(3) ++ Nil = List(1, 2, 3)
def flatMap[A, B](list: List[A])(f: A => List[B]): List[B] = list match {
// ++ appends two Lists, so the reason flatMap flattens is that the List returned by f
// is appended onto the front of the List returned by flatMap. So append is the flattener.
case (x::xs) => f(x) ++ flatMap(xs)(f)
case _ => Nil
}
// flatten more simply shows through its signature how flatMap works using append.
// Given a List of Lists, pluck off the head of each inner-List and append it to the remaining flattened List.
def flatten[B](list: List[List[B]]): List[B] = list match {
case (x::xs) => x ++ flatten(xs)
case _ => Nil
}
// map is basically just building a List of values:
// 1 :: 2 :: 3 :: Nil = List(1, 2, 3)
// even if those values are themselves Lists:
// List(1) :: List(2) :: List(3) :: Nil = List(List(1), List(2), List(3))
def map[A, B](list: List[A])(f: A => B ) : List[B] = list match {
// :: appends a _value_ to a List so the reason map does not flatten is that
// the _value_ returned by f is appended verbatim to the front of the List returned by map.
case (x::xs) => f(x) :: map(xs)(f)
case _ => Nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment