Ranges, Progressions and step

Ranges, Progressions and step in Kotlin: A draper's cutting bench is a long table with a brass rule let into the top, graduated in millimetres from one end to…

The Analogy: The Draper's Bench and the Two Brass Stops

A draper's cutting bench is a long table with a brass rule let into the top, graduated in millimetres from one end to the other, and two brass stops that slide along a groove beside it and clamp down wherever you want them. To cut a length of cloth you slide the first stop to the mark where the piece begins, the second to the mark where it ends, lay the cloth against both, and run the knife along the far edge of the second stop. The stops are the whole apparatus: they turn a number in a cutting list into two physical positions on a table.

Setting them is where the craft lives, because a graduation on the rule is a position, not a quantity. If you clamp one stop at 1 and the other at 1200, the cloth between them covers marks 1 to 1200 inclusive, which is 1200 millimetres of cloth. If you clamp them at 0 and 1200 you have covered 1201 marks and cut a piece one millimetre long. Both settings look identical from two feet away, both produce a piece that a casual eye would call twelve hundred, and only one of them is right. The rule also has a row of small notches punched every fifty millimetres for repeat work: slide the stop from notch to notch and you get a run of even lengths without measuring each one, and the last notch you can actually reach may be short of the second stop rather than level with it.

The bench works in both directions. A cutter who is coming to the end of a roll works from the far end backwards, sliding the stops down the rule instead of up, and the same two numbers describe the same span whichever way the knife travels. What the bench will not do is invent cloth. Clamp the first stop at 500 and the second at 100 and there is no span between them at all -- not a negative piece, not a reversed piece, simply nothing to cut, and the honest thing for the cutter to do is put the knife down.

The failure mode is the one every apprentice meets and no ledger records. A new hand is shown the bench, told the stops go "at the start and the end", and clamps them at 0 and at the length -- one millimetre generous, every single time. Each piece passes inspection, because a millimetre is inside anyone's tolerance and the piece measures what the ticket says to the nearest sensible unit. But the roll is a fixed length, and after a hundred pieces the shop is a hundred millimetres of cloth short with no cut to blame it on: no single piece is wrong, the sum is wrong. That is the difference between 1..1200 and 1 until 1200 in Kotlin, and it is why the language gives you two spellings and makes you choose one.


Syntax or Core Structure

A range is built with .. between two ends, and it is an ordinary object you can name, pass around and ask questions of. 1..10 is an IntRange holding both ends; 1 until 10 stops one short of the second; 10 downTo 1 runs the other way; and step turns any of them into a progression that skips. All of them can be walked with for and tested with in, which is the same operator the compiler uses for a when branch.

fun main() {
    val cut = 1..10
    val open = 1 until 10
    val back = 10 downTo 1
    val every3 = 1..10 step 3

    println("closed: " + cut.first + ".." + cut.last + " count " + cut.count())
    println("open: " + open.first + ".." + open.last + " count " + open.count())
    println("down: " + back.first + ".." + back.last + " step " + back.step)
    println("every 3: " + every3.joinToString(" "))
    println("last of every 3: " + every3.last)

    val empty = 5..1
    println("empty: " + empty.isEmpty() + " count " + empty.count())

    println("7 in cut: " + (7 in cut) + "  10 in open: " + (10 in open))
    println("letters: " + ('a'..'f').joinToString(""))
    println("longs: " + (1L..3L).joinToString(" "))
}

Output:

closed: 1..10 count 10
open: 1..9 count 9
down: 10..1 step -1
every 3: 1 4 7 10
last of every 3: 10
empty: true count 0
7 in cut: true  10 in open: false
letters: abcdef
longs: 1 2 3

Read the second line carefully: 1 until 10 reports its last as 9, not 10. until does not remember that you wrote 10 and mark the end as excluded -- it builds a closed range whose end is one lower, which is why 10 in open is false and why the count is 9. The third line shows that downTo produces an IntProgression rather than a range, with a step of -1; the direction lives in the step, not in the order of the ends. The fourth and fifth lines are the notched rule from the bench: 1..10 step 3 yields 1, 4, 7 and 10, and here the last notch happens to land exactly on the far stop. The empty case is the crossed stops -- 5..1 is not an error and not a reversed range, it is a range with nothing in it, and isEmpty() says so. The last three lines are the same machinery on other types: Char and Long have ranges of their own, and in works on all of them.


Technical Depth: Range, Progression, and the Adjusted last

Kotlin has two related ideas here and mixing them up causes most of the confusion. A range is a pair of ends with a membership test: it answers "is this value between the two stops". A progression is a walk: a start, a step and an end, which yields a specific sequence of values. IntRange is both, because it is a range whose step is 1. 1..10 step 3 is only a progression -- you can walk it, but its contains is the range's, so it will tell you 5 is inside even though the walk never lands on 5.

ExpressionWhat it makesBoth ends includedNotes
1..10IntRangeyesthe step is 1
1 until 10IntRangeend excludedends at 9; the usual loop bound
1..<10IntRangeend excludedthe operator spelling, Kotlin 1.8 and later
10 downTo 1IntProgressionyesthe step is -1
1..10 step 3IntProgressionstart yes, end only if reachablehere 10 is reachable
'a'..'f'CharRangeyesordered by code point
1L..3LLongRangeyesLong has its own range type
1.0..2.0ClosedFloatingPointRangeyessupports in, cannot be walked

The property that surprises people is last. On a progression it is not the number you typed as the second end; it is the last value the walk actually reaches, computed once when the progression is built and stored. That is a feature, not an accident: it means last is always a value the loop will visit, so for (i in p) ... and p.last never disagree.

Progression written asValues it yieldsIts last property
1..10 step 31, 4, 7, 1010
1..11 step 31, 4, 7, 1010, not 11
1..9 step 41, 5, 99
10 downTo 1 step 410, 6, 22, not 1
5..1none at all1, while first is 5, so isEmpty is true

The adjusted end, and the progression that yields nothing

fun main() {
    val labels = listOf("1..10 step 3", "1..11 step 3", "1..9 step 4", "10 downTo 1 step 4")
    val walks = listOf(1..10 step 3, 1..11 step 3, 1..9 step 4, 10 downTo 1 step 4)

    for (i in walks.indices) {
        val p = walks[i]
        println(labels[i] + " -> " + p.joinToString(" ") +
            "  first " + p.first + " last " + p.last + " step " + p.step + " count " + p.count())
    }

    val crossed = 5..1
    println("5..1 -> first " + crossed.first + " last " + crossed.last +
        " empty " + crossed.isEmpty() + " count " + crossed.count())

    val rev = (1..10 step 3).reversed()
    println("reversed -> " + rev.joinToString(" ") + " first " + rev.first +
        " last " + rev.last + " step " + rev.step + " count " + rev.count())
}

Output:

1..10 step 3 -> 1 4 7 10  first 1 last 10 step 3 count 4
1..11 step 3 -> 1 4 7 10  first 1 last 10 step 3 count 4
1..9 step 4 -> 1 5 9  first 1 last 9 step 4 count 3
10 downTo 1 step 4 -> 10 6 2  first 10 last 2 step -4 count 3
5..1 -> first 5 last 1 empty true count 0
reversed -> 10 7 4 1 first 10 last 1 step -3 count 4

The first two lines are the same four values from two different sources. Writing 11 as the end changed nothing, because 13 would overshoot and 10 is therefore the last reachable value in both cases; the stored last reports 10 either way. That is exactly the notched rule: the last notch you can reach may sit short of the stop. The fourth line shows the same adjustment running downwards, and note that step prints -4 -- you wrote step 4 and Kotlin stored the direction in the sign. Line five is the crossed stops: first is still 5 and last is still 1, because those are the ends you gave, but isEmpty() is true and the count is 0, so a for over it does nothing at all rather than failing. The last line shows reversed() swapping the ends and negating the step. It starts from the progression's stored last, not from the number you typed as the end, so a reversed 1..11 step 3 would also begin at 10. The identity that ties every non-empty line together is last == first + step * (count - 1).

Ranges you can test but never walk

Not every range is a walk. 1.0..2.0 builds a ClosedFloatingPointRange<Double>, which answers in correctly and has start and endInclusive properties, but there is no for loop over it -- there is no sensible "next" for a Double. More generally, any type that implements Comparable gets .. for free through an extension on Comparable, which means a domain type of yours becomes a range endpoint the moment you write compareTo.

class Length(val mm: Int) : Comparable<Length> {
    override fun compareTo(other: Length): Int = mm.compareTo(other.mm)
}

fun main() {
    val tolerance = 0.98..1.02
    for (r in listOf(0.97, 0.99, 1.00, 1.03)) {
        println("reading " + r + " in tolerance: " + (r in tolerance))
    }

    val stock = Length(900)..Length(1500)
    val bolt = Length(1200)
    val offcut = Length(400)
    println("stock " + stock.start.mm + " mm to " + stock.endInclusive.mm + " mm")
    println("bolt " + bolt.mm + " mm in stock: " + (bolt in stock))
    println("offcut " + offcut.mm + " mm in stock: " + (offcut in stock))

    val grades = "A".."F"
    println("C in grades: " + ("C" in grades) + "  Z in grades: " + ("Z" in grades))
    println("tolerance start " + tolerance.start + " end " + tolerance.endInclusive)
}

Output:

reading 0.97 in tolerance: false
reading 0.99 in tolerance: true
reading 1.0 in tolerance: true
reading 1.03 in tolerance: false
stock 900 mm to 1500 mm
bolt 1200 mm in stock: true
offcut 400 mm in stock: false
C in grades: true  Z in grades: false
tolerance start 0.98 end 1.02

Two things in that output repay attention. The third line prints 1.0 although the source says 1.00, because the literal is a Double and Double.toString gives the shortest form that round-trips -- the range test is unaffected, but a log line that has to match a fixture will bite you. And "A".."F" is a range over String, ordered by String.compareTo, so it is a comparison test and not a set of six letters: "C" is inside because it sorts between "A" and "F", "Z" is outside, and "ABC" would also be inside, which is almost never what someone reaching for "A".."F" had in mind.


Real World Example: Cutting a Roll to a Cutting List

const val CUTS = "COAT:1200:1202,SKIRT:700:698,VEST:450:450,SLEEVE:300:303,CUFF:120:118"
const val ROLL_MM = 4000
const val KERF = 5
const val TOL = 3

const val W_PIECE = 8
const val W_TARGET = 7
const val W_ACTUAL = 7
const val W_SHORT = 6
const val W_FROM = 6
const val W_TO = 6
const val W_STATUS = 8

val STATUSES = listOf("PASS", "FAIL")

fun statusFor(short: Int): String = if (short in 0..TOL) "PASS" else "FAIL"

fun row(piece: String, target: String, actual: String, short: String,
        from: String, to: String, status: String): String =
    piece.padStart(W_PIECE) + target.padStart(W_TARGET) + actual.padStart(W_ACTUAL) +
        short.padStart(W_SHORT) + from.padStart(W_FROM) + to.padStart(W_TO) +
        status.padStart(W_STATUS)

fun main() {
    val width = W_PIECE + W_TARGET + W_ACTUAL + W_SHORT + W_FROM + W_TO + W_STATUS
    val records = CUTS.split(",")
    val tally = IntArray(STATUSES.size)
    var cursor = 1
    var totalTarget = 0
    var totalActual = 0
    var totalShort = 0
    var lastEnd = 0

    println(row("PIECE", "TARGET", "ACTUAL", "SHORT", "FROM", "TO", "STATUS"))
    println("-".repeat(width))

    for (record in records) {
        val parts = record.split(":")
        val piece = parts[0]
        val target = parts[1].toInt()
        val actual = parts[2].toInt()
        val short = target - actual
        val status = statusFor(short)
        val span = cursor until cursor + actual

        tally[STATUSES.indexOf(status)]++
        totalTarget += target
        totalActual += actual
        totalShort += short
        lastEnd = span.last
        cursor = span.last + 1 + KERF

        println(row(piece, target.toString(), actual.toString(), short.toString(),
            span.first.toString(), span.last.toString(), status))
    }

    val kerfTotal = records.size * KERF
    val used = totalActual + kerfTotal
    val remnant = ROLL_MM - used

    println("-".repeat(width))
    println(row("TOTALS", totalTarget.toString(), totalActual.toString(),
        totalShort.toString(), "--", used.toString(),
        tally[0].toString() + " OF " + records.size))
    println("status: " + STATUSES.mapIndexed { i, s -> s + "=" + tally[i] }.joinToString(" "))
    println("roll " + ROLL_MM + " mm  cloth " + totalActual + " mm  kerf " + kerfTotal +
        " mm  remnant " + remnant + " mm")
    println("cloth " + totalActual + " + kerf " + kerfTotal + " + remnant " + remnant +
        " = " + (totalActual + kerfTotal + remnant) +
        " agree: " + (totalActual + kerfTotal + remnant == ROLL_MM))
    println("last cut ends at " + lastEnd + "  next start would be " + cursor)
}

Output:

   PIECE TARGET ACTUAL SHORT  FROM    TO  STATUS
------------------------------------------------
    COAT   1200   1202    -2     1  1202    FAIL
   SKIRT    700    698     2  1208  1905    PASS
    VEST    450    450     0  1911  2360    PASS
  SLEEVE    300    303    -3  2366  2668    FAIL
    CUFF    120    118     2  2674  2791    PASS
------------------------------------------------
  TOTALS   2770   2771    -1    --  2796  3 OF 5
status: PASS=3 FAIL=2
roll 4000 mm  cloth 2771 mm  kerf 25 mm  remnant 1204 mm
cloth 2771 + kerf 25 + remnant 1204 = 4000 agree: true
last cut ends at 2791  next start would be 2797

The program is the bench, walked once from end to end. cursor holds the millimetre mark where the next piece begins, starting at 1 because the rule's first graduation is a position and not a quantity. For each record the span of cloth the piece occupies is cursor until cursor + actual, and that single expression is the whole reason until exists: a piece of 1202 mm laid down at mark 1 covers marks 1 to 1202, so the range that describes it must exclude cursor + actual. Had the code written cursor..cursor + actual, every FROM and TO pair on the board would still look plausible and every piece would be recorded one millimetre longer than it is.

The FROM and TO columns are just span.first and span.last, which is why they read as inclusive marks a cutter could clamp a stop to. Between one piece and the next the cursor advances by span.last + 1 + KERF: one to step off the last millimetre of cloth, then five for the blade. You can audit that from the printed board alone -- 1202 plus 6 is 1208, 1905 plus 6 is 1911, and so on down the FROM column -- and the final line closes the loop by showing where the sixth piece would have started, 2797, which is one past the 2796 millimetres the TOTALS row says are gone.

The bottom four lines are the shop's accounting. The tally is an IntArray indexed through STATUSES rather than a map, so the order of PASS=3 FAIL=2 is fixed by the declaration and not by a hash. The cloth total 2771 is the sum of the ACTUAL column, the kerf total is five cuts at 5 mm, and the remnant is what the roll has left. The reconciliation line adds them and gets 4000, agreeing with ROLL_MM.

That agreement is worth less than it looks, and the board hides something worse. The verdict comes from statusFor, which tests short in 0..TOL -- and short is target - actual, so a positive value means the piece came out short of its ticket. A range starting at 0 therefore passes any piece up to 3 mm short and fails every piece that is over-length by even one millimetre. That is not a tolerance, it is a one-sided test pointing the wrong way for a cloth shop: an over-length piece can be trimmed, an under-length piece is scrap for that garment. Look at the board and you can see it happening -- the COAT, 2 mm generous, is stamped FAIL, while the SKIRT, 2 mm mean, is stamped PASS, and the SLEEVE fails at 3 mm over when a piece 3 mm under would have passed. The fix is one character short of trivial, short in -TOL..TOL for a symmetric check, and nothing in the arithmetic would change: the verdicts never feed the totals, so agree: true prints either way. Two smaller limits sit alongside it. remnant is never tested for being negative, and because cloth + kerf + remnant == ROLL_MM is an algebraic identity rather than a measurement, a cutting list longer than the roll would print a negative remnant and still report agree: true. And STATUSES.indexOf(status) returns -1 for any status string not in the list, which would make tally[-1]++ throw rather than mis-file the row -- safe today only because statusFor has exactly two return values.


Common Mistakes

  1. Using .. where the bound is a size. for (i in 0..items.size) walks one index past the end and throws on the last iteration. A size is an exclusive bound: use 0 until items.size, or better items.indices, which cannot be got wrong.
  1. Believing last is the number you typed. For 1..11 step 3 the last is 10. The progression stores the last value the walk actually reaches, so code that uses p.last as "the end of the run" is right and code that uses it as "the limit I configured" is wrong.
  1. Writing a descending range with ... 10..1 is not 10 down to 1, it is an empty range, and a for over it silently does nothing. Descending needs downTo, and the absence of an error here is what makes it expensive.
  1. Passing a negative number to step. 10 downTo 1 step -1 throws IllegalArgumentException at runtime: step must be positive, and the direction comes from downTo. The sign you see in p.step is an output, not an input.
  1. Trying to iterate a floating-point range. 1.0..2.0 supports in but has no iterator, so for (x in 1.0..2.0) does not compile. Walk integers and scale them, which also spares you the accumulating error of repeated addition.
  1. Using a range that starts at 0 to express a tolerance. diff in 0..TOL is one-sided. A symmetric requirement is diff in -TOL..TOL; if the requirement really is one-sided, write the range that says so and name the constant accordingly.
  1. Treating contains on a stepped progression as membership of the walk. 5 in (1..10 step 3) is true, because contains is inherited from the range's ends, while the walk yields 1, 4, 7 and 10 and never visits 5. If you mean "does the walk land here", test the arithmetic or use any.
  1. Calling count() on a huge range. IntRange is not a Collection, so count() iterates every element. On 1..2_000_000_000 that is a two-second no-op. The count of a progression is arithmetic: derive it from first, last and step.
  1. Reading a String range as a set of characters. "A".."F" is a ClosedRange<String> ordered by compareTo, so "ABC" in "A".."F" is true. For six letters you want 'A'..'F', a CharRange, and the single quotes are the entire difference.

Best Practices

  • Reach for indices before 0 until size, and for withIndex or a direct for (item in items) before either. The index you never write is the index you never get wrong.
  • Use until (or ..< if your Kotlin is 1.8 or later) whenever the second number is a count, a size or a capacity, and reserve .. for cases where both numbers are real positions a person could point at.
  • Give a range a name when it is used more than once. val valid = 900..1500 then if (mm in valid) reads better than two comparisons and, more importantly, means the bounds exist in exactly one place.
  • Prefer x in a..b over x >= a && x <= b. It compiles to the same two comparisons, it cannot be written with one operator accidentally strict, and it makes the intent -- membership -- explicit.
  • Write tolerances as a symmetric range around zero, -TOL..TOL, or with abs(diff) <= TOL. If the rule genuinely is asymmetric, use two named constants so the asymmetry is a decision on the page rather than an artefact of where the range starts.
  • Never iterate a floating-point range. Walk an Int progression and divide, so the values are exact and the count is predictable.
  • Derive the size of a large progression arithmetically instead of calling count(), and test isEmpty() rather than comparing count() to zero -- isEmpty() is a single comparison of the two ends.
  • Implement Comparable on domain types that have a natural order. You get .., in, coerceIn, minOf, maxOf and sorting from one compareTo, and callers can express a valid band as a range instead of a pair of loose values.

Practice Exercises

  1. Fix the one-sided tolerance in the cutting-list program. Add a second verdict column computed with short in -TOL..TOL, keep the original beside it, and print how many of the five rows the two columns disagree on. Confirm that the reconciliation line still says agree: true, and write one sentence explaining why that line was never going to catch the bug.
  1. Write a function describe(p: IntProgression): String that returns the first value, the last value, the step and the count, and have it assert p.last == p.first + p.step * (p.count() - 1) before returning. Run it over 1..10 step 3, 1..11 step 3, 7 downTo 1 step 2 and 5..1, and make the empty case return something honest instead of failing the assertion.
  1. Replace the var cursor in the cutting-list program with a progression. Build a list of the FROM marks first, using a running total, then walk it with for (i in marks.indices) so no mutable cursor survives in the loop body. Print the FROM column both ways and check the two lists are equal.
  1. Give a Reading(val micron: Int) class a compareTo, then express a machine's acceptance band as a Reading range and classify a list of ten readings as BELOW, IN or ABOVE using only in and the range's start and endInclusive. Print a tally of the three verdicts and prove it sums to ten.