In Scala Seq
, there is a lengthCompare
method which returns the comparison between the Seq
length and a given Int
without computing the length of the Seq
.
It is implemented in the trait SeqLike
as follows:
/** Compares the length of this $coll to a test value.
*
* @param len the test value that gets compared with the length.
* @return A value `x` where
* {{{
* x < 0 if this.length < len
* x == 0 if this.length == len
* x > 0 if this.length > len
* }}}
* The method as implemented here does not call `length` directly; its running time
* is `O(length min len)` instead of `O(length)`. The method should be overwritten
* if computing `length` is cheap.
*/
def lengthCompare(len: Int): Int = {
if (len < 0) 1
else {
var i = 0
val it = iterator
while (it.hasNext) {
if (i == len) return if (it.hasNext) 1 else 0
it.next()
i += 1
}
i - len
}
}
Since this implementation only requires an iterator
, why isn't it defined in IterableLike
?
That would make it available in Seq
, Set
and Map
collections.
There is one in the new and greatly overhauled Scala 2.13 collections that was released just yesterday, see here. The simple reason is that plenty of things about the Scala collections just weren't the way they ought to be, which has now been fixed. The fact that it exists in the new version indicates that it wasn't an active choice to exclude it previously.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With