Created
January 16, 2016 09:16
-
-
Save guersam/86d3574e696d711587e1 to your computer and use it in GitHub Desktop.
foldLeft
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
def flatMap[A](list: List[A], f: A => List[A]) = | |
list.foldLeft(List.empty[A]) { (acc, x) => acc ++ f(x) } | |
assert( | |
flatMap(1 :: 2 :: 3 :: Nil, (x: Int) => x :: x :: Nil) == | |
List(1, 1, 2, 2, 3, 3) | |
) | |
def max[A: Ordering](list: List[A]): Option[A] = | |
list match { | |
case Nil => None | |
case hd :: tl => Some(tl.foldLeft(hd)(Ordering[A].max)) | |
} | |
assert(max((1 to 10).toList) == Some(10)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment