From 8077d69b9f47df65f33a5979b45cd28cdb6bc5c2 Mon Sep 17 00:00:00 2001 From: satorg Date: Wed, 14 Dec 2022 23:38:56 -0800 Subject: [PATCH] fix in Range --- .../main/scala/cats/collections/Range.scala | 23 +++++++++++-------- 1 file changed, 14 insertions(+), 9 deletions(-) diff --git a/core/src/main/scala/cats/collections/Range.scala b/core/src/main/scala/cats/collections/Range.scala index cb3368c2..adef2cf8 100644 --- a/core/src/main/scala/cats/collections/Range.scala +++ b/core/src/main/scala/cats/collections/Range.scala @@ -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 @@ -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)) } /** @@ -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))