0
votes

Can Julia functions match a specific symbol rather than just a type Symbol? For example:

function test(x::Symbol(:ALPHA)) end
function test(x::Symbol(:BETA)) end

The above is what I was trying to accomplish, though the syntax is wrong.

1
Maybe Val is what you need.jverzani
Or just an if :)StefanKarpinski
are you about pattern matching? No, it not implement in Julia, but you can look on this: github.com/toivoh/julia-pattern-dispatch and this matchjl.readthedocs.io/en/latestuser4651282
See docs.julialang.org/en/latest/manual/performance-tips/… (though I agree, you may need it in your case).Andy Hayden

1 Answers

3
votes

Do you really want an additional version of the function to be compiled for each symbol? An additional compilation is quite expensive, and the compiler will have to put in a branch anyway... you will not gain any performance by dispatching on the value.

Instead, you should probably write code like this:

function test(x::Symbol)
    if x == :ALPHA
         ...
    elseif x == :BETA
         ...
    else
         throw(ArgumentError("Expected :ALPHA or :BETA"))
    end
end

or if you don't like how this looks, consider using pattern matching with Match.jl:

test(x::Symbol) = @match x begin
    :ALPHA => ...
    :BETA  => ...
    _      => throw(ArgumentError("Expected :ALPHA or :BETA"))
end

If you really need dispatch, you can use a type to wrap around the value, like Val{:ALPHA}. This type needs to be created at the caller site. In 99% of situations, this is a bad idea. Remember that this does not prevent the branch when calling the function, and in fact makes it slower since dispatch is more expensive than a branch.