InlineDispatch.jl – A simple module to perform dispatch on the value of an expression

Based on a discussion here on Discourse, I’m happy to announce a new package called InlineDispatch.jl for dispatching on values using anonymous functions.

The following expression:

    @dispatch expr begin
        v::Type1 -> body1...
        v::Type2 -> body2...
    end

performs a dispatch on the value of expr.

The dispatch uses the anonymous functions in the block as methods, and returns the value of the appropriate body expression. The order of the functions doesn’t matter, the most specific match is chosen, as customary with Julian dispatch.

Examples

julia> @dispatch 42 begin
           i::Integer -> "int $i"
           r::Real    -> "real $r"
           ::Nothing  -> "nothing"
       end
"int 42"

julia> @dispatch π begin
           i::Integer -> "int $i"
           r::Real    -> "real $r"
           ::Nothing  -> "nothing"
       end
"real π"

julia> @dispatch "foo" begin
           i::Integer -> "int $i"
           r::Real    -> "real $r"
           ::Nothing  -> "nothing"
       end
ERROR: @dispatch: Unmatched type String!

It can be particularly useful in try ... catch blocks to handle various types
of errors.

julia> try
           do_some_stuff()
       catch exn
           @dispatch exn begin
               e::AssertionError -> println(stderr, "AssertionError: ", e.msg)
               ::InexactError    -> println(stderr, "InexactError")
               _                 -> rethrow()
           end
       end

It’s just that! A simple module for a simple task. Happy dispatching!

15 Likes