Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

LinearSeq lengthCompare without an iterator.

Had to fix up an iffy test: not only was it testing undefined
behavior, it demanded just the right numbers be printed in a
context where all negative or positive numbers are equivalent.
It's the ol' "get them coming and going" trick.
  • Loading branch information...
commit 13643815fe41b17e931be9d0a8906200b0147a23 1 parent 24a033b
@paulp paulp authored
View
22 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.
@@ -248,19 +249,16 @@ trait LinearSeqOptimized[+A, +Repr <: LinearSeqOptimized[A, Repr]] extends Linea
override /*SeqLike*/
def lengthCompare(len: Int): Int = {
- // TODO: Remove this method when incrementing a major revision
- // This method is the same as in SeqLike, no need to redefine it
- 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
+ @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)
}
+ if (len < 0) 1
+ else loop(0, this)
}
override /*SeqLike*/
View
4 test/files/run/t2544.check
@@ -2,8 +2,8 @@
2
3
3
--2
--2
+-1
+-1
1
1
0
View
22 test/files/run/t2544.scala
@@ -1,19 +1,25 @@
object Test {
object Foo extends Seq[Int] {
def apply(i: Int) = i
- def length = 4
+ def length = 5
def iterator = Iterator(0,1,2,3,4)
}
+ def lengthEquiv(result: Int) = println(
+ if (result < 0) -1
+ else if (result == 0) 0
+ else 1
+ )
+
def main(args: Array[String]) = {
println(Foo indexWhere(_ >= 2,1))
println(Foo.toList indexWhere(_ >= 2,1))
println(Foo segmentLength(_ <= 3,1))
println(Foo.toList segmentLength(_ <= 3,1))
- println(Foo lengthCompare 7)
- println(Foo.toList lengthCompare 7)
- println(Foo lengthCompare 2)
- println(Foo.toList lengthCompare 2)
- println(Foo lengthCompare 5)
- println(Foo.toList lengthCompare 5)
+ lengthEquiv(Foo lengthCompare 7)
+ lengthEquiv(Foo.toList lengthCompare 7)
+ lengthEquiv(Foo lengthCompare 2)
+ lengthEquiv(Foo.toList lengthCompare 2)
+ lengthEquiv(Foo lengthCompare 5)
+ lengthEquiv(Foo.toList lengthCompare 5)
}
-}
+}
Please sign in to comment.
Something went wrong with that request. Please try again.