I am amazed by the value type in Julia and hence wrote a blog post about it. During the writing, some idea came to my mind, and I’ll express it as follows.
I want to define the root function in a weird way
root( x::Float64, ::Val{n} ) where n
which calculates x^{1/n}.
This allows me not only to generate one piece of machine code for each integer n, but also to define some weird root methods, such as “cat root” and “dog root”:
root( x::Float64, ::Val{:cat} ) = "Meow"
root( x::Float64, ::Val{:dot} ) = "Bark"
Then I can call
root(2.0, Val(a))
which will be dispatched differently according to the value of a.
Although flexible, it still has some limitation. In the first method, if root has different behaviors for Integer n and AbstractFloat n, or for positive n and negative n, is it possible to dispatch accordingly, say, by
root( x::Float64, ::Val{n} ) where {n::Integer}
root( x::Float64, ::Val{n} ) where {n::AbstractFloat}
root( x::Float64, ::Val{n} ) where {n::Integer > 0}
root( x::Float64, ::Val{n} ) where {n::Integer < 0}
?
I am conscious that similar use cases may be rare. So, is it actually a good idea, or I overstretched?
My blog post can be found here.