# How to do literal dispatch?

**URL:** <https://discourse.julialang.org/t/how-to-do-literal-dispatch/111493>\
**Category:** General Usage\
**Created:** [March 11, 2024, 11:29pm UTC](https://discourse.julialang.org/t/how-to-do-literal-dispatch/111493 "2024-03-11T23:29:39Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![putianyi888](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/putianyi888/32/32279_2.png) [@putianyi888](https://discourse.julialang.org/u/putianyi888)\
**Post date:** [March 11, 2024, 11:29pm UTC](https://discourse.julialang.org/t/how-to-do-literal-dispatch/111493/1 "2024-03-11T23:29:39Z")

</div>

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.

---

<div class="post-metadata">

**Author:** ![benninkrs](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/benninkrs/32/3191_2.png) [@benninkrs](https://discourse.julialang.org/u/benninkrs)\
**Post date:** [March 11, 2024, 11:46pm UTC](https://discourse.julialang.org/t/how-to-do-literal-dispatch/111493/2 "2024-03-11T23:46:26Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![jar1](https://avatars.discourse-cdn.com/v4/letter/j/c0e974/32.png) [@jar1](https://discourse.julialang.org/u/jar1)\
**Post date:** [March 12, 2024, 12:03am UTC](https://discourse.julialang.org/t/how-to-do-literal-dispatch/111493/3 "2024-03-12T00:03:21Z")

</div>

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

```julia
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
))))

```

---

<div class="post-metadata">

**Author:** ![CameronBieganek](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/cameronbieganek/32/6915_2.png) [@CameronBieganek](https://discourse.julialang.org/u/CameronBieganek)\
**Post date:** [March 12, 2024, 12:48am UTC](https://discourse.julialang.org/t/how-to-do-literal-dispatch/111493/4 "2024-03-12T00:48:26Z")

</div>

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/types/#%22Value-types%22)

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