Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/joomla/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Scala 从一个范围到另一个范围采样_Scala_Scala Collections - Fatal编程技术网

Scala 从一个范围到另一个范围采样

Scala 从一个范围到另一个范围采样,scala,scala-collections,Scala,Scala Collections,我想使用另一个范围对一个范围进行“采样”。例如: def sample(in: Range, by: Range): Range = ??? // note: Range equals broken! assert(sample(3 to 10 , 1 to 2 ).toVector == (4 to 5 ).toVector) assert(sample(3 to 10 , 1 to 4 by 2).toVector == (4 to 6 by 2).toVe

我想使用另一个
范围
对一个
范围
进行“采样”。例如:

def sample(in: Range, by: Range): Range = ???

// note: Range equals broken!
assert(sample(3 to 10     , 1 to 2     ).toVector == (4 to 5     ).toVector)
assert(sample(3 to 10     , 1 to 4 by 2).toVector == (4 to 6 by 2).toVector)
assert(sample(3 to 10 by 2, 1 to 2     ).toVector == (5 to 7 by 2).toVector)
assert(sample(3 to 10 by 2, 1 to 4 by 2).toVector == (5 to 9 by 4).toVector)

如何定义
示例
方法?

这里是一个尝试。我还没有测试所有可能的组合。为简单起见,
by
参数的起点必须大于或等于零,并且必须有一个正步长

def sample(in: Range, by: Range): Range = {
  val drop  = by.start
  val stepM = by.step
  require(drop >= 0 && stepM > 0)
  val in1 = in.drop(drop)
  val in2 = if (stepM == 1) 
    in1 
  else if (in1.isInclusive)  // copy-method is protected :(
    new Range.Inclusive(start = in1.start, end = in1.end, step = in1.step*stepM)
  else
    new Range          (start = in1.start, end = in1.end, step = in1.step*stepM)
  in2.take(by.size)
}

通过将
sample
返回类型更改为
IndexedSeq[Int]
,得到了这个简单的解决方案

def sample(in: Range, by: Range): IndexedSeq[Int] = {
  in intersect (in.start+by.start to in.start+by.end by by.step)
}
它搜索
in
by
之间的交集,并在
in.start
中移动

对于相应重构的断言,这两个

assert(sample(3 to 10     , 1 to 2     ) == (4 to 5     ))
assert(sample(3 to 10     , 1 to 4 by 2) == (4 to 6 by 2))
这两个都失败了

assert(sample(3 to 10 by 2, 1 to 2     ) == (5 to 7 by 2)) // intersect at 5 only
assert(sample(3 to 10 by 2, 1 to 4 by 2) == (5 to 9 by 4)) // empty intersect

我的尝试变得太混乱了,试图在所有情况下都是正确的。