Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Just to flesh out the answers, you could also define this as a recursive function using pattern matching:</p> <pre><code>def flatMap[A, B](list: List[A])(f: A =&gt; List[B]): List[B] = list match { case (x::xs) =&gt; f(x) ++ flatMap(xs)(f) case _ =&gt; Nil } </code></pre> <p>Or make it explicitly tail-recursive:</p> <pre><code>import scala.annotation.tailrec def flatMapTailRec[A, B](list: List[A])(f: A =&gt; List[B]): List[B] = { @tailrec def _flatMap(result: List[B])(input: List[A])(f: A =&gt; List[B]): List[B] = input match { case (x::xs) =&gt; _flatMap(f(x) ++ result)(xs)(f) case _ =&gt; result } _flatMap(List[B]())(list)(f) } </code></pre> <p>I did a bit of quick, non-rigorous benchmarking, using sample input of:</p> <pre><code>val input = (0 to 1000).map(_ =&gt; (0 to 1000).toList).toList </code></pre> <p>In order from fastest to slowest:</p> <ul> <li><code>flatMap(input)(x =&gt; x)</code> <ul> <li><strong>0.02069937453</strong> seconds</li> </ul></li> <li><code>flatMapTailRec(input)(x =&gt; x)</code> <ul> <li><strong>0.02335651054</strong> seconds</li> </ul></li> <li><code>input.flatMap(x =&gt; x)</code> <ul> <li><strong>0.0297564358</strong> seconds</li> </ul></li> <li><code>flatMapFoldLeft(input)(x =&gt; x)</code> <ul> <li><strong>12.940458234</strong> seconds</li> </ul></li> </ul> <p>I'm a little surprised that <code>foldLeft</code> comes out so much slower than the others. It would be interested to see how <code>flatMap</code> is actually defined in the source. I tried looking myself, but there's too much to go through at the moment >_>.</p> <p><strong>Edit</strong>: As Daniel Sobral pointed out in the comments of another answer, these implementations are restricted to <code>List[A]</code>. You could write a more generic implementation that would work for any mappable type. The code would quickly become much more complicated.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload