diff options
author | Paul Phillips <paulp@improving.org> | 2012-12-28 19:56:59 -0800 |
---|---|---|
committer | Paul Phillips <paulp@improving.org> | 2012-12-28 19:56:59 -0800 |
commit | 99a58775a93e650be12973c72e72beda7b1c2af2 (patch) | |
tree | a9646c5c5b945049e248629ffb61099009b2d6ef /src | |
parent | 1284c3c6f38cc419a0a39fd68b3d5cf81b36b1a5 (diff) | |
parent | 13643815fe41b17e931be9d0a8906200b0147a23 (diff) | |
download | scala-99a58775a93e650be12973c72e72beda7b1c2af2.tar.gz scala-99a58775a93e650be12973c72e72beda7b1c2af2.tar.bz2 scala-99a58775a93e650be12973c72e72beda7b1c2af2.zip |
Merge pull request #1828 from paulp/pr/stream-lengthCompare
SI-6415, Stream#lengthCompare
Diffstat (limited to 'src')
-rwxr-xr-x | src/library/scala/collection/LinearSeqOptimized.scala | 18 | ||||
-rw-r--r-- | src/library/scala/collection/SeqLike.scala | 16 |
2 files changed, 21 insertions, 13 deletions
diff --git a/src/library/scala/collection/LinearSeqOptimized.scala b/src/library/scala/collection/LinearSeqOptimized.scala index 0f0a405a85..81cccea519 100755 --- a/src/library/scala/collection/LinearSeqOptimized.scala +++ b/src/library/scala/collection/LinearSeqOptimized.scala @@ -12,6 +12,7 @@ import generic._ import mutable.ListBuffer import immutable.List import scala.util.control.Breaks._ +import scala.annotation.tailrec /** A template trait for linear sequences of type `LinearSeq[A]` which optimizes * the implementation of several methods under the assumption of fast linear access. @@ -247,14 +248,17 @@ trait LinearSeqOptimized[+A, +Repr <: LinearSeqOptimized[A, Repr]] extends Linea } override /*SeqLike*/ - def lengthCompare(len: Int): Int = { - var i = 0 - var these = self - while (!these.isEmpty && i <= len) { - i += 1 - these = these.tail + def lengthCompare(len: Int): Int = { + @tailrec def loop(i: Int, xs: Repr): Int = { + if (i == len) + if (xs.isEmpty) 0 else 1 + else if (xs.isEmpty) + -1 + else + loop(i + 1, xs.tail) } - i - len + if (len < 0) 1 + else loop(0, this) } override /*SeqLike*/ diff --git a/src/library/scala/collection/SeqLike.scala b/src/library/scala/collection/SeqLike.scala index f65e2ef9cd..1be0dba29f 100644 --- a/src/library/scala/collection/SeqLike.scala +++ b/src/library/scala/collection/SeqLike.scala @@ -84,13 +84,17 @@ trait SeqLike[+A, +Repr] extends Any with IterableLike[A, Repr] with GenSeqLike[ * if computing `length` is cheap. */ def lengthCompare(len: Int): Int = { - var i = 0 - val it = iterator - while (it.hasNext && i <= len) { - it.next() - i += 1 + 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 } - i - len } override /*IterableLike*/ def isEmpty: Boolean = lengthCompare(0) == 0 |