Re: Why does for(x <- c; y = ...) yield {...} become c.map(x => (x, ...)).map((x,y) => {...})
Rex Kerr <[email protected]>
| Newsgroups | gmane.comp.lang.scala |
|---|---|
| Message-ID | <CAP_xLa1qwp4fmuE7MmJTTj97wQsLZ=OQZrx_LwtwdqeLE6_6vg@mail.gmail.com> |
The decomposition of inside the yield is no fun either when you look at the
bytecode. Consider
for (x <- xs; l = x.length) yield { x(0)+l }
for (x <- xs) yield { val l = x.length; x(0) + l }
Same thing, right? Except the top one takes twice as long because of the
double-map. Similarly,
for (x <- xs; c = x(x.length-1); if c < '5') yield x
for (x <- xs if x(x.length-1) < '5') yield x
xs.collect{ case x if x(x.length-1) < '5' => x }
val nb = Coll.newBuilder[A]; xs.foreach(x => if (x(x.length-1) < '5') nb
+= x); nb.result
all do the same thing. But they vary by a factor of 5 as to which is the
fastest, and which is which depends on the collection. The first one is
always slowest, though.
I think a serious revisiting of the desugaring is appropriate. I am a
little hesitant to recommend anything when moving to SAMs may change what
is possible / efficient.
--Rex
On Sat, Jan 24, 2015 at 11:07 AM, Haoyi Li <[email protected]> wrote:
> I've been looking at http://docs.scala-lang.org/tutorials/FAQ/yield.html,
> and found this
>
> for(x <- c; y = ...) yield {...}
>
> is translated into
>
> c.map(x => (x, ...)).map((x,y) => {...})
>
>
> This seems rather odd to me. Why not
>
> for(x <- c; y = ...) yield {...}
>
> is translated into
>
> c.flatMap{ x => val y = ...; {...} }
>
>
> Isn't this basically the same, but much more straightforward?
>
> The reason I bumped into this is that I was trying to implement a bunch of
> custom for-comprehension generators, and it kept asking for *.map*, and I
> couldn't figure out why. These were pretty odd generators, e.g. a TryCatch
> generator which you can put anywhere in your loop and which propagates a
> Seq() back up if it catches an exception, and so don't really have
> meaningful values to pass into *map* or *flatMap*s.
>
> --
> You received this message because you are subscribed to the Google Groups
> "scala-language" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to [email protected].
> For more options, visit https://groups.google.com/d/optout.
>
--
You received this message because you are subscribed to the Google Groups "scala-language" group.
To unsubscribe from this group and stop receiving emails from it, send an email to [email protected].
For more options, visit https://groups.google.com/d/optout.