Is there a difference between flatten and flatMap (personality)?

scala> List(List(1), List(2), List(3), List(4)) res18: List[List[Int]] = List(List(1), List(2), List(3), List(4)) scala> res18.flatten res19: List[Int] = List(1, 2, 3, 4) scala> res18.flatMap(identity) res20: List[Int] = List(1, 2, 3, 4) 

Is there a difference between the two? When is it advisable to use one over the other? Are there any compromises?

+5
source share
3 answers

You can view flatMap(identity) as map(identity).flatten . (Of course, this is not implemented this way, as it will take two iterations).

map(identity) gives you the same collection, so at the end it is the same as flatten .

I would personally stick with flatten , as it is shorter / easier to understand and design to do this.

+4
source

Conceptually, there is no difference. In practice, flatten more efficient and provides a clearer intention.

Typically, you do not use identity directly. This is more where situations such as passing as a parameter, or the default setting. It is possible for the compiler to optimize it, but you risk an extra function call for each element.

You should use flatMap when you need to execute map (with a function other than identity ) followed by flatten .

+3
source

Conceptually there is no difference in the results ... flatMap takes a bit more time to get the same result ...

I will show it more practical with an example of flatMap , map , and then flatten and flatten

  object Test extends App {
   // flatmap
   println (timeElapsed (List (List (1, 2, 3, 4), List (5, 6, 7, 8)). flatMap (identity)))
   // map and then flatten
   println (timeElapsed (List (List (1, 2, 3, 4), List (5, 6, 7, 8)). map (identity) .flatten))
   // flatten
   println (timeElapsed (List (List (1, 2, 3, 4), List (5, 6, 7, 8)). flatten))

   / **
    * timeElapsed
    * /
   def timeElapsed [T] (block: => T): T = {
     val start = System.nanoTime ()
     val res = block
     val totalTime = System.nanoTime - start
     println ("Elapsed time:% 1d nano seconds" .format (totalTime))
     res
   }
 }


Both flatMap and flatten execute with the same result after repeating several times

Conclusion: flatten effective

  Elapsed time: 2915949 nano seconds
 List (1, 2, 3, 4, 5, 6, 7, 8)
 Elapsed time: 1060826 nano seconds
 List (1, 2, 3, 4, 5, 6, 7, 8)
 Elapsed time: 81172 nano seconds
 List (1, 2, 3, 4, 5, 6, 7, 8)
+3
source

Source: https://habr.com/ru/post/1207170/


All Articles