Efficient definition of function which uses fixed allocated constants

I need to define a whole group of functions, each of which depends on large heap allocated arrays which do not change run to run. While I could declare these arrays const, this clutters the namespace as the array names used are similar for each function, and defining a separate module to separate the namespace for each is something I would rather not do. Here is a toy example of such a definition:

const B = [1,2,45,3]
non_alloc_const(x) = sum(x^a for a in B)

However, declaring the arrays within the function leads to them being reallocated each time, as in the function below, which is undesirable given the size of the arrays.

function alloc(x)
    A = [1,2,45,3]
    return sum(x^a for a in A)
end

And something like the below code does exactly what I want, but I tend to develop by repeatedly executing the code in the same REPL in vscode, so an error is thrown as the const is redefined every time. Removing the const makes the function a non-constant global and rather slow.

const non_alloc_let = let
    A = [1,2,45,3]
    g(x) = sum(x^a for a in A)
end

Is there another, easier way to define such a function? Am I missing something obvious?

How about a callable struct, aka functor?

julia> struct SumPowers{V<:AbstractVector}
           A::V
       end

julia> (sp::SumPowers)(x::Number) = sum(x^a for a in sp.A)

julia> A = [1, 2, 45, 3];

julia> sp = SumPowers(A)
SumPowers{Vector{Int64}}([1, 2, 45, 3])

julia> sp(1.1)
76.53148368510332
2 Likes

You can make the function global directly like this:

let A = [1,2,45,3]
    global g(x) = sum(x^a for a in A)
end
2 Likes