Create Range with inclusive end value when stepping
Create Range with inclusive end value when stepping
Is there any way to create a range which includes the end value when using a step which doesn't align?
For instance the following yields:
scala> Range.inclusive(0, 35, 10)
res3: scala.collection.immutable.Range.Inclusive = Range(0, 10, 20, 30)
But I would also like the end value (35) included like so:
scala> Range.inclusive(0, 35, 10)
res3: scala.collection.immutable.Range.Inclusive = Range(0, 10, 20, 30, 35)
3 Answers
3
No, not with the current definition/ implementation. It would be strange behaviour to have the step the same for all intermediate elements but different from the last.
Depending on whether you really need the indices, you could use
.grouped
(I regard explicit indices in a loop as often a code smell)– The Archetypal Paul
May 25 '16 at 20:54
.grouped
As mentioned, not a standard semantics. A workaround,
for (i <- 0 to 35 by 10) yield if (35 % 10 != 0 && 35 - i < 10) 35 else i
where you must replace the boundary and step values as needed.
Thanks for this workaround could come in handy although I'm going to revisit my approach and come up with a cleaner solution.
– Fred Smith
May 25 '16 at 19:32
The above solution does not work because it omits the value "30". Here is a unfold-style solution that produces a list rather than a sequence.
def unfoldRange(i: Int, j: Int, s: Int): List[Int] = {
if (i >= j) List(j)
else i :: unfoldRange(i+s,j,s)
}
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Yes that makes sense - however I was considering a use case where a collection (table) could be effectively partitioned into chunks using column indexes. thanks.
– Fred Smith
May 25 '16 at 19:30