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.
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.
Val
is what you need. – jverzaniif
:) – StefanKarpinski