For in Racket

Racket provides several looping constructs. Here are some basic types of loops.

#lang racket

; The most basic type, with a single condition.
(let loop ([i 1])
  (when (<= i 3)
    (displayln i)
    (loop (+ i 1))))

; A classic initial/condition/after loop.
(for ([j (in-range 3)])
  (displayln j))

; Another way of accomplishing the basic "do this N times" iteration.
(for ([i (in-range 3)])
  (displayln (format "range ~a" i)))

; A loop that continues until a break condition is met.
(let loop ()
  (displayln "loop")
  (break))

; You can also continue to the next iteration of the loop.
(for ([n (in-range 6)])
  (when (even? n)
    (continue))
  (displayln n))

When you run this program, you’ll see:

$ racket for.rkt
1
2
3
0
1
2
range 0
range 1
range 2
loop
1
3
5

Let’s break down the different types of loops:

  1. The first loop uses a named let to create a recursive loop. It’s similar to a while loop in other languages.

  2. The second loop uses for with in-range to iterate over a sequence of numbers. This is equivalent to a C-style for loop.

  3. The third loop is another example of using for with in-range, demonstrating how to iterate a specific number of times.

  4. The fourth loop shows how to create an infinite loop that can be broken out of. In this case, we break immediately after the first iteration.

  5. The last loop demonstrates how to skip iterations using continue. In Racket, we use when with continue to achieve this.

Note that Racket doesn’t have built-in break or continue statements. In real Racket code, you would typically use more idiomatic constructs like tail recursion or higher-order functions instead of explicit loop control.

We’ll see some other loop forms later when we look at list comprehensions, sequences, and other data structures.