Implementing List#flatMap

functional-programming, scala

Solution

An alternate approach:

def flatMap[A, B](list: List[A])(f: A => List[B]): List[B] =
  list.foldLeft(List[B]())(_ ++ f(_))

I don't know about “better”. (And if we start talking about efficient implementation, that's another can of worms...)

Problem

Is there a better functional way to write `flatMap`? ``` def flatMap[A,B](list: List[A])(f: A => List[B]): List[B] = list.map(x => f(x)).flatten ``` Conceptually, I understand `flatMap` in terms of `flatten`.

Original source