When is it installed less than the other in Scala?

I wanted to compare the power of two sets in Scala. Since the material “just works” in Scala, I tried using < between sets. It seems to pass, but I cannot make any sense out of the result.

Example:

 scala> Set(1,2,3) < Set(1,4) res20: Boolean = true 
  • What does he return?
  • Where can I read about this method in the API?
  • Why is it not listed anywhere in scala.collection.immutable.Set ?

Update: even the order (??) of elements in sets matters:

 scala> Set(2,3,1) < Set(1,3) res24: Boolean = false scala> Set(1,2,3) < Set(1,3) res25: Boolean = true 
+4
source share
3 answers

This does not work with 2.8. On Scala 2.7, the following happens:

 scala.Predef.iterable2ordered(Set(1, 2, 3): Iterable[Int]) < (Set(1, 3, 2): Iterable[Int]) 
In other words, there is an implicit conversion defined on scala.Predef that is “imported” for all Scala code, from Iterable[A] to Ordered[Iterable[A]] , provided that there is an implicit A => Ordered[A] .

Given that the iterability order for sets is undefined, you cannot strongly predict this. If you add elements to make the set size more than four, for example, you will get completely different results.

+5
source

If you want to compare power, just do it directly:

 scala> Set(1, 2, 3).size < Set(2, 3, 4, 5).size res0: Boolean = true 
+1
source

My knowledge of Scala is not extensive, but by doing some tests, I get the following:

 scala> Set(1,2) < <console>:5: error: missing arguments for method < in trait Ordered; follow this method with `_' if you want to treat it as a partially applied function Set(1,2) < ^ 

This tells me that < comes from the Ordered attribute. Additional tips:

 scala> Set(1,2) < _ res4: (Iterable[Int]) => Boolean = <function> 

That is, Set evaluates to Iterable because there may be some implicit conversion from Iterable [A] to Ordered [Iterable [A]], but I'm not sure anymore ... Tests are incompatible. For example, these two may offer a kind of lexicographic comparison:

 scala> Set(1,2,3) < Set(1,2,4) res5: Boolean = true 

1 equals, 2 equals, 3 is less than 4.

 scala> Set(1,2,4) < Set(1,2,3) res6: Boolean = false 

But this is not so:

 scala> Set(2,1) < Set(2,4) res11: Boolean = true scala> Set(2,1) < Set(2,2) res12: Boolean = false 

I think the correct answer is that it is found in the Ordered : there is no implementation for < between sets more than comparing their hashCode:

It is important that the hashCode method for an instance of Ordered [A] is compatible with the comparison method. However, it is not possible to provide a reasonable default implementation. Therefore, if you need to calculate the hash of an Ordered [A] instance, you must provide it yourself either during installation or when creating the instance.

0
source

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


All Articles