# Multiple dispatch and "x^-n equivalent to inv(x)^n for literal n"

**URL:** <https://discourse.julialang.org/t/multiple-dispatch-and-x-n-equivalent-to-inv-x-n-for-literal-n/14303>\
**Category:** General Usage\
**Tags:** question\
**Created:** [August 30, 2018, 11:09am UTC](https://discourse.julialang.org/t/multiple-dispatch-and-x-n-equivalent-to-inv-x-n-for-literal-n/14303 "2018-08-30T11:09:17Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![xzackli](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/xzackli/32/38301_2.png) [@xzackli](https://discourse.julialang.org/u/xzackli)\
**Post date:** [August 30, 2018, 11:09am UTC](https://discourse.julialang.org/t/multiple-dispatch-and-x-n-equivalent-to-inv-x-n-for-literal-n/14303/1 "2018-08-30T11:09:17Z")

</div>

Applying a negative integer exponent calls `inv`, from [pull request #24240](https://github.com/JuliaLang/julia/pull/24240).

I have a custom type based on a string, which I would like to exponentiate, for example

```julia
struct LaTeXobj
    latex_string::String
end

x = LaTeXobj("x+3")

Base.:^( lo::LaTeXobj, p::Number ) = "($(lo.latex_string))^{$p}"
x^(-3)

```

The desired result would be a string `"(x+3)^{-3}"`, but this instead calls `inv`. It looks like some metaprogramming is going on in `literal_pow` which confusingly prevents my usual approach with operators from working.

```julia
MethodError: no method matching inv(::LaTeXobj)
Closest candidates are:
  inv(!Matched::Complex{Float64}) at complex.jl:396
  inv(!Matched::BigFloat) at mpfr.jl:418
  inv(!Matched::Integer) at int.jl:56
  ...

Stacktrace:
 [1] macro expansion at ./none:0 [inlined]
 [2] literal_pow(::typeof(^), ::LaTeXobj, ::Val{-3}) at ./none:0
 [3] top-level scope at none:0

```

How do you implement the exponent symbol for a custom type and negative integer exponents? I could just use a symbol other than `^`, but I was really hoping for that slick syntactic sugar!

---

<div class="post-metadata">

**Author:** ![Sukera](https://avatars.discourse-cdn.com/v4/letter/s/ce7236/32.png) [@Sukera](https://discourse.julialang.org/u/Sukera)\
**Post date:** [August 30, 2018, 11:23am UTC](https://discourse.julialang.org/t/multiple-dispatch-and-x-n-equivalent-to-inv-x-n-for-literal-n/14303/2 "2018-08-30T11:23:27Z")

</div>

One way would be to define `literal_pow` for `literal_pow(f::typeof(^), x::LaTeXobj, ::Val{p})`:

```julia
julia> struct LaTeXobj
           latex_string::String
           end

julia> x = LaTeXobj("x+3")
LaTeXobj("x+3")

julia> Base.literal_pow(f::typeof(^), x::LaTeXobj, ::Val{p}) where {p} = "($(x.latex_string))^{$p}"

julia> x^(-3)
"(x+3)^{-3}"

julia> x^3
"(x+3)^{3}"

```

But I agree, this feels backwards…

On a sidenote, I think you’ll take interest in [LaTeXStrings.jl](https://github.com/stevengj/LaTeXStrings.jl).
