Re: Sorted structures lose their ordering when mapped

Stephen Compall <[email protected]> Thu, 15 Dec 2016 15:52:14 -0800
Newsgroups gmane.comp.lang.scala
Message-ID <[email protected]>
On 11/30/16 1:30 PM, Tobin Yehle wrote:
> Thanks for the examples Stephen, that makes a lot of sense. If not 
> having typeclass coherence causes such problems would it be possible 
> to give a compiler warning if someone like me breaks it?
No, sorry, not with Scala's current design.

> It looks like for all the examples I gave it would be better to just 
> put an implicit reversed order in the local scope. eg:
> implicit val revOrd = Ordering.Int.reverse
> val set = SortedSet(1,2,3)
> set.map(_*2) // TreeSet(6,4,2)
> set.map(i => i -> "a"*i)(breakOut):SortedMap[Int, String] // TreeMap(3 
> -> aaa, 2 -> aa, 1 -> a)
>
> Is this style considered best practice?
Not really, because you don't get a warning if you forgot the difference.

scala> import scalaz.ISet, scalaz.Tags.Dual, scalaz.Dual._, scalaz.std.anyVal._


I can work with both forwards and backwards sets in the same scope.

scala> val s1 = ISet fromList List(4, 1, 7)
s1: scalaz.ISet[Int] = Bin(4,Bin(1,Tip(),Tip()),Bin(7,Tip(),Tip()))

scala> val s2 = ISet fromList Dual.subst(List(4, 1, 7))
s2: scalaz.ISet[scalaz.@@[Int,scalaz.Tags.Dual]] = Bin(4,Bin(7,Tip(),Tip()),Bin(1,Tip(),Tip()))

scala> s1.toAscList
res2: List[Int] = List(1, 4, 7)

scala> s2.toAscList
res3: List[scalaz.@@[Int,scalaz.Tags.Dual]] = List(7, 4, 1)


And if I forget (the equivalent to "put an implicit reversed order in 
the local scope" would be "import Dual._"), I get a compiler error:

scala> import scalaz.ISet, scalaz.Tags.Dual, scalaz.std.anyVal._

scala> val s1 = ISet fromList List(4, 1, 7)
s1: scalaz.ISet[Int] = Bin(4,Bin(1,Tip(),Tip()),Bin(7,Tip(),Tip()))

scala> val s2 = ISet fromList Dual.subst(List(4, 1, 7))
<console>:16: error: could not find implicit value for parameter o: scalaz.Order[scalaz.@@[Int,scalaz.Tags.Dual]]
        val s2 = ISet fromList Dual.subst(List(4, 1, 7))
                      ^

-- 
Stephen Compall
If anyone in the MSA is online, you should watch this flythrough.


-- 
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.