🎓 A1Learner
🔍
0 of 48 lessons completed

Julia Generated Functions

A generated function is a function whose body runs at compile time and returns code for Julia to run. The returned code is simple, and the choice inside the body is fixed.

A generated body chooses code at compile time

The body checks the value inside Val. It returns one piece of quoted code or another.

@generated function pick(::Val{N}) where N
  return N > 0 ? :(1) : :(0)
end
println(pick(Val(2)))
println(pick(Val(-1)))

The choice can test for zero

The body tests the value for zero. It returns quoted true or quoted false.

@generated function iszero_val(::Val{N}) where N
  return N == 0 ? :(true) : :(false)
end
println(iszero_val(Val(0)))
println(iszero_val(Val(3)))

The returned code can carry the value

The value is placed into the quoted code. The run then adds 10 to it.

@generated function valplus(::Val{N}) where N
  return :($N + 10)
end
println(valplus(Val(5)))

Example

@generated function pick(::Val{N}) where N
  return N > 0 ? :(1) : :(0)
end
@generated function valplus(::Val{N}) where N
  return :($N + 10)
end
println(pick(Val(3)))
println(pick(Val(-2)))
println(valplus(Val(4)))

Key points

  • Generated function: define one with @generated, and its body runs at compile time.
  • Return: the body must return quoted code, not a plain value.
  • Choice: the body can choose different quoted code from the value inside Val.
  • Compile time: the choice is made before the function runs, from its Val argument.
  • Result: the run uses the returned code, so the answer is a plain value.

In this example, pick returns 1 for a positive value and 0 for a negative value. Valplus places 4 into its code and adds 10.

Note

keep a generated body tiny, with one clear choice.

Try it Yourself

Edit the code, then press Run.

Running is simulated · JuliaHub

Exercise

What does pick(Val(-1)) give when pick returns 1 for a positive value and 0 otherwise?