🎓 A1Learner
🔍
0 of 47 lessons completed

Julia Staged Programming

Staged programming is generated functions used as compile-time code generation. It lets one function build different code for different types before the program runs.

A macro gives the same answer for every type

The macro returns the same quoted code no matter what value it receives.

macro same_label(x)
    return :( "same" )
end
println(@same_label 5)
println(@same_label "hi")

A staged function gives different answers by type

The generated body checks the type and returns quoted code for each case.

@generated function staged_label(x::T) where T
    if T <: Integer
        return :( "whole" )
    elseif T == String
        return :( "text" )
    else
        return :( "other" )
    end
end
println(staged_label(5))
println(staged_label("hi"))
println(staged_label(2.5))

A staged function builds different arithmetic by type

Whole numbers add to themselves, and other numbers scale by two.

@generated function staged_double(x::T) where T
    if T <: Integer
        return :(x + x)
    else
        return :(x * 2.0)
    end
end
println(staged_double(21))
println(staged_double(2.5))

Example

macro same_label(x)
    return :( "same" )
end
@generated function staged_label(x::T) where T
    if T <: Integer
        return :( "whole" )
    elseif T == String
        return :( "text" )
    else
        return :( "other" )
    end
end
println(@same_label 5)
println(@same_label "hi")
println(staged_label(5))
println(staged_label("hi"))

Key points

  • Staged code: Code built at compile time from type information.
  • Macro contrast: A macro transforms syntax before type information is known.
  • Macro limit: A macro never sees a type, so it cannot choose by type.
  • Generated view: A generated function sees types but never sees values.
  • One function: One staged function can serve many types with different built code.
  • Use staged programming to build type-specific code from one definition.

In this example, the macro gives same for both inputs, the staged function gives whole for 5, and the staged function gives text for hi.

Note

The caller still writes one normal call, even when the built code differs by type.

Try it Yourself

Edit the code, then press Run.

Running is simulated · JuliaHub

Exercise

How does staged programming differ from a macro?