There is a lengthCompare method in Scala Seq that returns a comparison between the length of the Seq and the given Int without calculating the length of the Seq .
It is implemented in the 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 is it not defined in IterableLike ?
This will make it available in the collections of Seq , Set and Map .
source share