Created
March 4, 2010 19:24
-
-
Save jrudolph/322035 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
final class MyRange(start: Int, limit: Int, step: Int) extends IndexedSeq[Int] { | |
val length: Int = { | |
def plen(start: Int, limit: Int, step: Int) = | |
if (limit <= start) 0 else (limit - start - 1) / step + 1 | |
if (step > 0) plen(start, limit, step) | |
else plen(limit, start, -step) | |
} | |
override def apply(idx: Int) = { | |
if (idx < 0 || idx >= length) throw new IndexOutOfBoundsException(idx.toString) | |
start + idx * step | |
} | |
override def foreach[U](f: Int => U) { | |
var i = start | |
while (if (step > 0) i < limit else i > limit) { | |
f(i) | |
i += step | |
} | |
} | |
} | |
object Test { | |
trait RangeBuilder { | |
def to2(limit: Int): MyRange | |
} | |
implicit def Int2Range(from: Int) = new RangeBuilder { def to2(limit:Int) = new MyRange(from, limit, 1) } | |
def testRange(b: Boolean) { | |
if (b) { | |
for (i <- 1 to2 5) | |
println(i) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment