Sometimes, one might want to unroll loops to optimize a program’s execution speed so that the program does less branching. Loops can be unrolled through a mixture of #insert
directives and macros. In this example below, we unroll a basic for loop that counts from 0 to 10.
unroll_for_loop :: (a: int, b: int, body: Code) #expand {
#insert -> string {
builder: String_Builder;
print_to_builder(*builder, "{\n");
print_to_builder(*builder, "`it: int;\n");
for i: a..b {
print_to_builder(*builder, "it = %;\n", i);
print_to_builder(*builder, "#insert body;\n");
}
print_to_builder(*builder, "}\n");
return builder_to_string(*builder);
}
}
unroll_for_loop(0, 10, #code {
print("%\n", it);
});