I have a function that essentially acts as a look-up table:
function lookup(a::Int64, x::Float64, y::Float64)
if a == 1
z = 2*x + y
else if a == 2
z = 5*x - 2*y
else if a == 3
...
end
return z
end
The variable a essentially determines what the relation of z is.
This function however takes a while to compile and is also not the most efficient at run time.
Could you compile the function lookup only for one instance of a (say a=1)? It is unlikely that this function will called for all possible functions of a.
I believe that such a functionality would be similar to templated functions in C++.
Julia's compiler can only dispatch on the type of arguments, not their value, as the value is only known at runtime. You can cheat a little by creating a "value type", where different values of a variable act as a different type:
lookup(::Type{Val{1}}, x, y) = 2x+y
lookup(::Type{Val{2}}, x, y) = 5x-2y
a = 2
lookup(Val{a}, 2, 3)
# 4
If you want to use this approach, you should read https://docs.julialang.org/en/stable/manual/performance-tips/#Types-with-values-as-parameters-1 first, to make sure it does not create issues with type-stability.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With