我有这样的东西:
case class FunctionsTest(lowerBound: Int = 1,
upperBound: Int = 1000,
factor: Int = 2) {
require(lowerBound < upperBound)
/**
* implement a sequence of ints, which start with lowerBound and end with
* upperbound.
*
* for all elements following should be true:
*
* xs(i) < xs(i+1)
* xs(i) + factor == xs(i + 1) (for i > 0 and i <= 1000)
*
*/
val xs: Seq[Int] = Seq.range(lowerBound,upperBound +1)
所以我需要这个类的序列,它构成了这些标准。。我用试过了
序列范围()
但它为我创建了适合第一个标准的序列,但我不知道现在如何应用评论中提到的第二个标准?
Seq.range[T](start: T, end: T, step)
的step
参数允许按因子增加。
scala> Seq.range(1,10,2)
res0: Seq[Int] = List(1, 3, 5, 7, 9)
这符合两个标准。
scala> res0.zip(res0.tail).forall(t => t._1 < t._2)
res4 Boolean = true
和
scala> res0(0) + 2 == res0(0 + 1)
res5: Boolean = true
通常,您可以使用iterate
:使用任意函数生成序列
Seq.iterate(1,1000)(_ + 2)
对于您的情况,任意函数相当于"a=a+2",它反复应用于起始值:1,1+2,(1+2)+2。。。
range方法允许您设置步长参数
Seq.range(lower, upper, factor)
您可以用一个简单的Range
创建它。
包括:(lowerBound to UpperBoud)
独占:(lowerBound until UpperBound)
如果你想要一个懒惰的评估器,有点像邮局等待的磁带计数器,你可以使用scala Stream
。它们非常节省内存,因为它们只存储Range的头部,并且只有在需要时才懒洋洋地评估尾部。他们的地图,过滤器,减少。。。函数也是惰性的。
scala.collection.immutable.Stream.range(lowerBound, upperBound)