Fred Smith
Fred Smith

Reputation: 23

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)

Upvotes: 2

Views: 738

Answers (4)

Tim Barrass
Tim Barrass

Reputation: 4939

I think you can tackle this by extending Range with the Pimp my Library pattern as well.

object Extensions {
  implicit def RichRange(value: Range) = new {
    def withEnd: IndexedSeq[Int] = {
      if (value.last != value.end) value :+ value.end
      else value
    }
  }
}

although you get an IndexedSeq[Int] rather than a range. Use it like:

import Extensions._
0 to 5 by 2 withEnd // produces 0, 2, 4, 5

Upvotes: 0

AJB0211
AJB0211

Reputation: 1

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)
}

Upvotes: 0

echo
echo

Reputation: 1291

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.

Upvotes: 1

The Archetypal Paul
The Archetypal Paul

Reputation: 41749

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.

Upvotes: 0

Related Questions