0__*_*0__ 3 scala scala-collections
是否有现有的功能可以改变Range生产另一种产品Range,例如
val r = 1 to 5
val s = r.map(_ + 2) // produces Vector(3, 4, 5, 6, 7)
Run Code Online (Sandbox Code Playgroud)
我想得到3 to 7.
以下是我将如何实现它:
implicit class RangeHasShift(val r: Range) extends AnyVal {
def shift(n: Int): Range = {
val start1 = r.start + n
val end1 = r.end + n
// overflow check
if ((n > 0 && (start1 < r.start || end1 < r.end)) ||
(n < 0 && (start1 > r.start || end1 > r.end)))
throw new IllegalArgumentException(s"$r.shift($n) causes number overflow")
if (r.isInclusive)
new Range.Inclusive(start1, end1, r.step)
else
new Range (start1, end1, r.step)
}
}
def check(r: Range) = assert(r == r.shift(123).shift(-123))
check(1 to 10)
check(1 to -1)
check(1 to -1 by -1)
check(1 to 10 by 3)
check(1 until 10)
check(1 until -1)
check(1 until -1 by -1)
check(1 until 10 by 3)
Run Code Online (Sandbox Code Playgroud)
我想知道这是否存在于API的某个地方?