InstanceDispatch
Documentation for InstanceDispatch.
InstanceDispatch.@instancedispatch — Macro
@instancedispatch myfunction(::T, args...; kwargs...)Write a specialized function to dispatch on instances values of type T. The only reauirement is that Type{T} has its own method for Base.instances.
You are allowed to chain dispatching, i.e. dispatching on multiple instancied types. This is done by having Any or Val parameter types prepending the enumeration. See examples.
Examples
@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 the following method:
function greet(e::GreetEnum, who)
if e == Hello
return greet(Val(Hello), who)
elseif
return greet(Val(Goodbye), who)
end
endYou can also dispatch on multiple enums. In that case, it is advised to explicitely state the types as much as possible.
@enum TitleEnum Citizen Comrade
title(::Val{Citizen}) = "citizen"
title(::Val{Comrade}) = "comrade"
function greet(::Val{Hello}, t::Val, who)
return join(["Hello", title(t), who], " ")
end
function greet(::Val{Goodbye}, t::Val, who)
return join(["Goodbye", title(t), who], " ")
end
@instancedispatch greet(::GreetEnum, t::TitleEnum, who)
@instancedispatch greet(::Val, t::TitleEnum, who)All the arguments in the function call given to the macro will be passed in the invocations. In case they are anonymous, new names will be created using gensym. where statements are supported.
It is important that there is a method for each instance of your enum, otherwise you might encounter errors, or worse, trigger the ire of JET.jl! It can be useful to define catch-all methods such as:
function greet(::Val, _, _)
#...
endThat returns a default value.
It is possible to use type annotations to help Julia figure out the type of the return value:
@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)::String