Search code examples
for-loopfunctional-programmingracketsequence

Racket: Difference between `range` and `in-range`


There are two possibilities to generate a sequence of numbers to be iterated in a for loop in Racket:

(for ([i (range 1 5)])
    (display i))

and

(for ([i (in-range 1 5)])
    (display i))

range and in-range both work and seem to be equivalent, but https://docs.racket-lang.org/reference/sequences.html says:

"An in-range application can provide better performance for number iteration when it appears directly in a for clause."

Does this also hold true in comparison to range?


Solution

  • Yes, range is equally performant as in-range when it syntactically appears directly in for clauses. In fact, range is simply transformed to in-range in that case.

    Note that while it's true that range and in-range are functionally equivalent when they appear in for clauses, they are not functionally equivalent in general.

    > (range 5)
    '(0 1 2 3 4)
    > (in-range 5)
    #<stream>