Julia Language Metaprogramming Until loop


Example

We're all used to the while syntax, that executes its body while the condition is evaluated to true. What if we want to implement an until loop, that executes a loop until the condition is evaluated to true?

In Julia, we can do this by creating a @until macro, that stops to execute its body when the condition is met:

macro until(condition, expression)
    quote
        while !($condition)
            $expression
        end
    end |> esc
end

Here we have used the function chaining syntax |>, which is equivalent to calling the esc function on the entire quote block. The esc function prevents macro hygiene from applying to the contents of the macro; without it, variables scoped in the macro will be renamed to prevent collisions with outside variables. See the Julia documentation on macro hygiene for more details.

You can use more than one expression in this loop, by simply putting everything inside a begin ... end block:

julia> i = 0;

julia> @until i == 10 begin
           println(i)
           i += 1
       end
0
1
2
3
4
5
6
7
8
9

julia> i
10