Skip to content

A simple Julia module to perform dispatch on a value of an expression using the `@dispatch` macro.

License

Notifications You must be signed in to change notification settings

dhanak/InlineDispatch.jl

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

9 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

CI codecov Aqua QA

InlineDispatch.jl

A simple module to perform dispatch on the value of an expression using the @dispatch macro.

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

Perform 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! @ REPL[3]:1

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

About

A simple Julia module to perform dispatch on a value of an expression using the `@dispatch` macro.

Topics

Resources

License

Stars

Watchers

Forks

Languages