Created
September 8, 2015 02:01
-
-
Save nicerobot/6213be207dd87b2d5e75 to your computer and use it in GitHub Desktop.
map vs flatMap
This file contains 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
// 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 | |
} |
This file contains 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
// 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 | |
} |
This file contains 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
// 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