Reputation: 1250
I have something like this:
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)
So I need a Sequence for this class which is making up these criteria.. I tried it with the
Seq.range()
but it creates me the Sequence which is right for the first criteria but I don't know how to now apply the second criteria mentioned in the comment?
Upvotes: 2
Views: 7568
Reputation: 15074
More generally, you can generate a sequence using an arbitrary function using iterate
:
Seq.iterate(1,1000)(_ + 2)
For your case, the arbitrary function amounts to "a = a + 2", which gets applied over and over to the start value: 1, 1+2, (1+2)+2, ...
Upvotes: 4
Reputation: 20285
The step
parameter of Seq.range[T](start: T, end: T, step)
allows you to increase by factor.
scala> Seq.range(1,10,2)
res0: Seq[Int] = List(1, 3, 5, 7, 9)
This satisfies both criteria.
scala> res0.zip(res0.tail).forall(t => t._1 < t._2)
res4 Boolean = true
and
scala> res0(0) + 2 == res0(0 + 1)
res5: Boolean = true
Upvotes: 6
Reputation: 17953
You can create it with a simple Range
.
inclusive : (lowerBound to UpperBoud)
exclusive : (lowerBound until UpperBound)
If you want a lazy evaluator, sort of like the tape counter for waiting at the post office, you can use scala Stream
. They are very memory efficient because they only store the head of the Range, and lazily evaluate the tail only when needed. Their map, filter, reduce, ... functions are also lazy.
scala.collection.immutable.Stream.range(lowerBound, upperBound)
Upvotes: 1
Reputation: 6385
range method allows you to set step parameter
Seq.range(lower, upper, factor)
Upvotes: 1