"for" translation into lists high order functions

As far as I understand, for expressions are translated into Scala expressions which are build upon:

High order lists methods.

A common example is the one where:

for(b1 <= books; b2 <- books if b1 != b2;
    a1 <- b1.authors; a2 <- b2.authors if a1 == a2) yield a1;

Results in:

books flatMap (b1 => 
    books withFilter( b2 => b1 != b2) flatMap( b2 => 
        b1.authors flatMap ( a1 => 
            b2.authors withFilter ( a2 => a2 == a1 ) map ( a2 => a1 )
        )
    )
)

Where:

My question is about this line:

b2.authors withFilter ( a2 => a2 == a1 ) map ( a2 => a1 )

Since the condition is a2 == a1 that line is equivalent to:

b2.authors withFilter ( a2 => a2 == a1 ) map ( x => x )

Why the generated code isn't just?

b2.authors filter ( a2 => a2 == a1 )

Can it be explained by the fact that the example is the reproduction of code automatically generated by Scala's compiler?

Is filter out of the for "building bricks"?

Upvotes: 2

Views: 82

Answers (1)

lmm
lmm

Reputation: 17431

The translation of for/yield syntax into method calls is very simple and mechanical, almost at the level of string manipulation. withFilter is necessary in some places for its laziness, therefore it's used everywhere for simplicity. I don't understand the phrasing of your final question, but for/yield expressions are AIUI never translated into calls to filter except in a deprecated way for objects that don't yet have a withFilter method.

Upvotes: 1

Related Questions