Julia Expert · Lesson 1 · On the house

Staged specialization

@generated bodies, Val{N} unrolling, and when to specialize. Lesson 1 is free — on the house.

Lessons · Julia Expert · Lesson 1 of 10 · On the house

Staged specialization

@generated bodies, Val{N} unrolling, and when to specialize.

Illustration for Julia
Lesson 1 is on the house.

Medium sketched @generated: the method sees types and returns an Expr. Expert work uses that to stage code — emit a different body per concrete signature, then let the compiler compile each specialization once.

Val{N} (and Val(N) values) smuggle a type-level constant into dispatch. A generated method on ::Val{N} can unroll a fixed-length loop into N statements when N is small and known at compile time.

Base.@assume_effects / effect annotations and careful purity matter: generated bodies must not observe runtime values. If you need a value, take it as a normal argument outside the generated path, or pass a Val that encodes the constant.

specialize / forcing specialization is usually automatic on concrete calls. Reach for @generated only when the shape of the code must change by type — field loads, unrolled tuples, static sizes — not for ordinary if on values.

Misses: reading runtime fields inside @generated, returning a non-Expr, or unrolling huge N so compile time explodes.

staged-specialization

@generated function sum_tuple(t::NTuple{N,Any}) where {N}
    exs = [:(s += t[$i]) for i in 1:N]
    quote
        s = 0
        $(Expr(:block, exs...))
        s
    end
end

println(sum_tuple((1, 2, 3)))
println(sum_tuple((10, 20)))

@generated function pow2(::Val{N}) where {N}
    :($(2^N))
end

println(pow2(Val(8)))
Match this when you type.

Quiz

What must a @generated method return?

Quiz

Why pass Val{N} into a generated method?

Quiz

What must you not do inside a @generated body?

Quiz

When is @generated the right tool?

Check

Match the still for: Staged specialization.

Open-book: the answers are on this page. Pass every quiz and check (5) to mark the lesson done. This visit: 0/5.