ClosedRange to Sequence

Hello,

What do you think is it worth adding the following extension to the Kotlin Library?

fun <T> ClosedRange<T>.toSequence(nextItem: (T) -> (T)) : Sequence<T> {
    generateSequence(nextItem.start) { prev ->
        val next = nextItem(prev)
        when {
            next <= endInclusive -> next
            else -> null
        }
     }
}

Usage:

fun ClosedRange<LocalDate>.getDays(): Sequence<LocalDate> {
      return toSequence {
           plusDays(1)
      }
}

KT-40934

1 Like

Your specific example doesn’t look very convincing, since toSequence must evaluate the next element before each range check:

// perfectly valid range, 
// throws DateTimeException because of LocalDate.MAX.plusDays(1)
(LocalDate.MAX..LocalDate.MAX).getDays().forEach {}  

That be solved easily enough

fun <T : Comparable<T>> ClosedRange<T>.toSequence(next: (T) -> T) =
    sequence {
        var value = start
        while (value != endInclusive) {
            yield(value)
            value = next(value)
        }
        yield(endInclusive)
    }

@westonal I don’t think you need the : Comparable<T> in this case then, but you have to be careful since the value might never == endInclusive (e.g. if we’re skipping by days and we start at 6pm and end at 4pm