jcrist / Juniper.jl

A simple computer algebra system, in Julia
Other
5 stars 0 forks source link

Use a macro to dispatch on Head #2

Open jcrist opened 9 years ago

jcrist commented 9 years ago

Juniper uses an Int8 to represent the type of the object, getting around the issue of dynamically dispatching on types. This means that some methods look like:

if expr.head == ADD
    do stuff
elseif expr.head == MUL
    do stuff
...

Ideally, this could be abstacted out with a macro, simplifying the logic. This could look something like the following may work?

@dispatch expr extra_args begin
    @case ADD func
    @case MUL func
    ...
end

This would then turn into:

if expr.head == ADD
    func(Val{ADD}, expr, extra_args)
elseif expr.head == MUL
    func(Val{MUL}, expr, extra_args)
...

Specific methods could then be written as:

function func(::Type{Val{MUL}}, expr::Symbolic, ...)

Because Val{...} is known at compile time, the calls to func will be fixed, and may even be inlined. This should prevent type instability, while also making such functions easier to read.

Note that this is extremely similar to the macro provided by Switch.jl, except it doesn't require break statements, and can be written in one line.

What I'd really like is if there was a way to do an actual switch statement, like in C, so that the long if...elseif... could be replaced with a computed goto. There doesn't seem to be such an option yet.

jcrist commented 9 years ago

This may be useful: https://github.com/toivoh/PatternDispatch.jl