Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Templated" functions for julia

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++.

like image 898
maero21 Avatar asked Apr 24 '26 17:04

maero21


1 Answers

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.

like image 58
Michael K. Borregaard Avatar answered Apr 27 '26 15:04

Michael K. Borregaard