For in Racket
Racket provides several looping constructs. Here are some basic types of loops.
When you run this program, you’ll see:
Let’s break down the different types of loops:
The first loop uses a named let to create a recursive loop. It’s similar to a while loop in other languages.
The second loop uses
for
within-range
to iterate over a sequence of numbers. This is equivalent to a C-style for loop.The third loop is another example of using
for
within-range
, demonstrating how to iterate a specific number of times.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.
The last loop demonstrates how to skip iterations using
continue
. In Racket, we usewhen
withcontinue
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.