Dotty: Set().map dangerous behavior due to information loss from return value

Created on 19 Jun 2019  路  3Comments  路  Source: lampepfl/dotty

val elements = Set(1,2,3)
val weights = Map(1 -> 1.0, 2 -> 1.0, 3 -> 1.0)
val values = Map(1 -> 0.2, 2 -> 0.6, 3 -> 0.4)

val wSum = elements.map(element=>
        weights(element) * values(element))
      .sum

wSum == 1.2 //True

Looks good so far

val elements = Set(1,2,3)
val weights = Map(1 -> 1.0, 2 -> 1.0, 3 -> 1.0)
val values = Map(1 -> 0.5, 2 -> 0.5, 3 -> 0.5)

val wSum = elements.map(element=>
        weights(element) * values(element))
      .sum

wSum == 1.5 //False, wSum = 0.5

Making elements a Seq fixes this since the result of the .map will be a Vector(3) instead of Set(1)

The wrong behavior here is discarding duplicate values in the return from .map() does not make any sense.

image

See how the image below can have different x map to same y. So by making the return type a Set, we are discarding this information. And in practice, this breaks my pretty common use case when Java HashMaps are involved.

This clones https://github.com/scala/bug/issues/11580, brought to discussion here

bug

Most helpful comment

So I guess this is where new discussion should take place

I'm afraid that's not the case, dotty development is only concerned about producing a compiler, and not about changing the standard library. In fact, the plan is for Scala 2.14 and 3.0 to use the exact same standard library to ease migration. A good place for open-ended discussion that don't fit in any particular tracker is https://contributors.scala-lang.org/.

All 3 comments

Dotty shares Scala 2's standard library and will continue to do so at least until Scala 3.0, so it's not necessary to open standard library tickets in both repos, the scala/bug ticket is sufficient.

I see the other ticket just got marked "won't fix" after your explanation on legacy design concerns. So I guess this is where new discussion should take place

So I guess this is where new discussion should take place

I'm afraid that's not the case, dotty development is only concerned about producing a compiler, and not about changing the standard library. In fact, the plan is for Scala 2.14 and 3.0 to use the exact same standard library to ease migration. A good place for open-ended discussion that don't fit in any particular tracker is https://contributors.scala-lang.org/.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

smarter picture smarter  路  3Comments

noti0na1 picture noti0na1  路  3Comments

ohze picture ohze  路  3Comments

m-sp picture m-sp  路  3Comments

odersky picture odersky  路  3Comments