Skip to content

Instantly share code, notes, and snippets.

@guersam
Created January 16, 2016 09:16
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 guersam/86d3574e696d711587e1 to your computer and use it in GitHub Desktop.
Save guersam/86d3574e696d711587e1 to your computer and use it in GitHub Desktop.
foldLeft
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