🎓 A1Learner
🔍
0 of 47 lessons completed

Julia Generated Functions in Depth

A generated function is a function whose body runs at compile time and returns code for the compiler to use. It can choose different code for different argument types.

A generated function returns different labels by type

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

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

A generated function builds different arithmetic by type

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

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

A generated function can answer true or false by type

The body returns quoted true for whole numbers and quoted false for other types.

@generated function is_whole(x::T) where T
    if T <: Integer
        return :(true)
    else
        return :(false)
    end
end
println(is_whole(5))
println(is_whole(2.5))
println(is_whole("hi"))

Example

@generated function kind(x::T) where T
    if T <: Integer
        return :( "integer" )
    elseif T == String
        return :( "text" )
    else
        return :( "other" )
    end
end
@generated function double_it(x::T) where T
    if T <: Integer
        return :(x + x)
    else
        return :(x * 2.0)
    end
end
println(kind(5))
println(double_it(21))
println(kind("hi"))
println(double_it(2.5))

Key points

  • Generated body: The body runs at compile time, not at run time.
  • Return rule: The body must return quoted code, not a plain value.
  • Type branch: The body can branch on the argument type to choose code.
  • Value limit: The body cannot read a runtime value, only its type.
  • Use @generated to mark a function whose body builds code at compile time.

In this example, kind labels 5 as integer and hi as text, double_it doubles 21 to 42, and double_it scales 2.5 to 5.0.

Note

A generated function still looks like a normal call to its caller.

Try it Yourself

Edit the code, then press Run.

Running is simulated · JuliaHub

Exercise

What does the body of a generated function return?