InstanceDispatch.jl is a single-macro package to mix enumerations (or anything that defines a method for Base.instances
) and dispatch-on-value in Julia.
Simply put it allows using dispatching in a type-stable fashion by writing code such as:
using InstanceDispatch
@enum GreetEnum Hello Goodbye
function greet(::Val{Hello}, who)
return "Hello " * who
end
function greet(::Val{Goodbye}, who)
return "Goodbye " * who
end
@instancedispatch greet(::GreetEnum, who)
This last line is equivalent to defining the following method:
function greet(e::GreetEnum, who)
if e == Hello
return greet(Val(Hello), who)
elseif e == Goodbye
return greet(Val(Goodbye), who)
else
end
end
This avoids the performance pit that you would encounter in simply writing:
function greet(e::GreetEnum, who)
return greet(Val(e), who)
end
import Pkg; Pkg.add("InstanceDispatch")
- ValSplit.jl essentially performs the same task for
Symbol
-based value type dispatch.