intermediate language-deep-dive

Iteration Patterns

Clean Language has several ways to iterate, each suited to a different problem. Ranges for counted loops, list iteration for collections, while for unknown counts. break and continue give you fine control when you need it.

Part of: How Clean works

Three iteration forms — range, step, and list:

start:
	string evens = ""
	iterate n in 2 to 10 step 2
		evens = evens + n.toString() + " "
	print("Evens: " + evens)

	list<string> days = []
	days.add("Mon")
	days.add("Tue")
	days.add("Wed")
	iterate day in days
		print("Day: " + day)

	integer n = 1
	integer total = 0
	while n <= 5
		total = total + n
		n = n + 1
	print("Sum 1-5: " + total.toString())
Evens: 2 4 6 8 10 
Day: Mon
Day: Tue
Day: Wed
Sum 1-5: 15

iterate n in 2 to 10 step 2 counts by twos. iterate day in days loops over every element by value — no index needed. while n <= 5 runs until the condition is false — use this when the count depends on logic.

break exits early; continue skips to the next iteration:

start:
	list<string> names = []
	names.add("Alice")
	names.add("Bob")
	names.add("Charlie")
	names.add("Diana")

	string search = "Charlie"
	integer found_at = -1
	iterate i in 0 to names.length() - 1
		if names[i] == search
			found_at = i
			break

	print(search + " at index: " + found_at.toString())

	string result = ""
	iterate name in names
		if name.length() < 5
			continue
		result = result + name + " "
	print("Long names: " + result)
Charlie at index: 2
Long names: Alice Charlie Diana 

break exits the iterate block immediately — the search stops as soon as Charlie is found. continue skips to the next iteration — names shorter than 5 characters are skipped. Both work in iterate-range, iterate-list, and while loops.

  • iterate n in start to end — range loop, inclusive on both ends
  • iterate n in start to end step N — count by N each iteration
  • iterate item in myList — loop over every element by value
  • break exits the loop; continue skips to the next iteration
📚 → Book 1, Chapter 9 : Language in Practice →
Copied!