Loops and Local Variables

This example calculates the same sum three ways, using for, while, and fold. The loop versions use local variables, showing that reassignment inside a function can still be part of a pure computation.


sum_for : List(I64) -> I64
sum_for = |numbers| {
	var $total = 0
	for n in numbers {
		$total = $total + n
	}
	$total
}

sum_while : List(I64) -> I64
sum_while = |numbers| {
	var $total = 0
	var $remaining = numbers
	while !$remaining.is_empty() {
		match $remaining {
			[n, .. as rest] => {
				$total = $total + n
				$remaining = rest
			}
			[] => break
		}
	}
	$total
}

sum_fold : List(I64) -> I64
sum_fold = |numbers| numbers.fold(0, |total, n| total + n)

expect sum_for([1, 2, 3]) == 6
expect sum_while([1, 2, 3]) == 6
expect sum_fold([1, 2, 3]) == 6
expect sum_while([]) == 0

The for version follows the items in the list, while the while version keeps going as long as there are items left. The fold version expresses the same calculation by passing the running total from one step to the next.

A var can only be reassigned inside the function that declares it. That local reassignment does not make the function effectful, so all three versions have the same pure function type.

Output

Run this from the directory that has main.roc in it:

$ roc test main.roc

All (4) tests passed in 11.4 ms.

Validated with Roc nightly-2026-10-29-a0a9fc2.