How to do literal dispatch?

I’d like to make a function dispatch on literal inputs, like how Base.^ dispatches on literal_pow, but I have no idea how it works. A quick search suggests it’s done by the compiler which means that my goal is not possible.

I don’t think you can dispatch on constants but the compiler is getting pretty good at compiling functions with constant inputs.

2 Likes

literal_pow is a special case that happens during lowering, so you can’t do it yourself:

julia> Meta.@lower  1 ^ 2
:($(Expr(:thunk, CodeInfo(
    @ none within `top-level scope`
1 ─ %1 = ^
│   %2 = Core.apply_type(Base.Val, 2)
│   %3 = (%2)()
│   %4 = Base.literal_pow(%1, 1, %3)
└──      return %4
))))
2 Likes

You can dispatch on “plain bits” values if you put them into a type parameter. See the docs for Val, etc.

https://docs.julialang.org/en/v1/manual/types/#"Value-types"

https://docs.julialang.org/en/v1/manual/performance-tips/#man-performance-value-type

4 Likes