Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use a macro to dispatch on Head #2

Open
jcrist opened this issue Feb 27, 2015 · 1 comment
Open

Use a macro to dispatch on Head #2

jcrist opened this issue Feb 27, 2015 · 1 comment

Comments

@jcrist
Copy link
Owner

jcrist commented Feb 27, 2015

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
Copy link
Owner Author

jcrist commented Feb 27, 2015

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant