Skip to content

Commit

Permalink
fix in Range
Browse files Browse the repository at this point in the history
  • Loading branch information
satorg committed Jan 9, 2023
1 parent c1fdc8b commit 8077d69
Showing 1 changed file with 14 additions and 9 deletions.
23 changes: 14 additions & 9 deletions core/src/main/scala/cats/collections/Range.scala
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,14 @@

package cats.collections

import cats.{Eq, Order, Show}
import cats.Eq
import cats.Order
import cats.Show

/**
* Represent an inclusive range [x, y] that can be generated by using discrete operations
*/
final case class Range[A](val start: A, val end: A) {
final case class Range[A](start: A, end: A) {

/**
* Subtract a Range from this range. The result will be 0, 1 or 2 ranges
Expand Down Expand Up @@ -77,13 +79,12 @@ final case class Range[A](val start: A, val end: A) {
* the start's successor.
*/
def toIterator(implicit discrete: Discrete[A], order: Order[A]): Iterator[A] = {
val next: A => A = a => if (order.lteqv(a, end)) discrete.succ(a) else discrete.pred(a)
val next: A => A = if (order.lt(start, end)) discrete.succ(_) else discrete.pred(_)

Stream
Iterator
.iterate(start)(next)
.takeWhile(concurrent => !order.eqv(concurrent, end))
.append(Seq(end))
.iterator
.takeWhile(order.neqv(_, end))
.++(Iterator.single(end))
}

/**
Expand All @@ -103,14 +104,18 @@ final case class Range[A](val start: A, val end: A) {
def contains(x: A)(implicit A: Order[A]): Boolean = A.gteqv(x, start) && A.lteqv(x, end)

/**
* Apply function f to each element in range [star, end]
* Apply function f to each element in range `[star, end]`. Does nothing if `end` precedes `start`.
*/
def foreach(f: A => Unit)(implicit discrete: Discrete[A], order: Order[A]): Unit = {
var i = start
while (order.lteqv(i, end)) {
// Visit values in range [start, end), i.e. excluding `end`.
while (order.lt(i, end)) {
f(i)
i = discrete.succ(i)
}
// Visit the last (or the only) value, if any.
if (order.eqv(i, end))
f(i)
}

def map[B](f: A => B): Range[B] = Range[B](f(start), f(end))
Expand Down

0 comments on commit 8077d69

Please sign in to comment.