[ANN] InstanceDispatch.jl: Dispatch-on-value with anyting that defines a `Base.instances` method

Hi there,
I just started the registration process for InstanceDispatch.jl, a single-macro package that writes for you a method that dispatches on methods with value-type from a type that defines a Base.instances method (typically an @enum). Say you have a function that behaves differently depending on a flag that has been passed to it (typically a finite state machine). For example

@enum GreetEnum Hello Goodbye

function greet(::Val{Hello}, who)
    return "Hello " * who
end
function greet(::Val{Goodbye}, who)
    return "Goodbye " * who
end

In your state machine you would like to store the flag as an instance of the enum, but then simply calling greet(Val(state), somename) is not type stable. This package automates the tedious task of writing and maintaining 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

Instead you can simply write:

@instancedispatch greet(::GreetEnum, who)

There’s also the possibility of dispatching on multiple enums, you can check the documentation!

6 Likes

This reminds me of ValSplit.jl

1 Like

Oh! indeed, I did not find this package when I was looking for a solution to this problem. This is essentially the same thing for symbol-based value types. I will add a link to ValSplit,jl in the README file.

1 Like