Overloading a function within a loop

This question is closely related to the package iTensors, but it is really a Julia programming question, no knowledge of the package is needed.

I need to overload a function provided by the package. The canonical way to do so (see Physics (SiteType) System Examples · ITensors.jl) is

ITensors.op(::OpName"Pup",::SiteType"S=1/2") = [1 0; 0 0]

Since I need to do this many times, I wanted to write a loop to do it. Specifically, I have a bunch of OpNames (just strings)

op_names = ["op1", "op2", "op3"]

and corresponding matrices (what is assigned on the right-hand side)

ops = [matrix1, matrix2, matrix3]

where for example matrix1 = [1 0; 0 0] et cetera as in the example above. So I tried the following, but this does not overload the function as expected. I’m sure I am making a mistake how exactly this should be done (scoping, evaluation, dealing with the quotation marks in the command, …)

for i in 1:length(op_names)
    name = op_names[i]
    matrix = ops[i]
    ex_string = "@eval ITensors.op(::OpName"*'"'*name*'"'*",::SiteType"*'"'*"Ququart"*'"'*") = matrix"
    eval(ex_string)
end
for i in 1:length(op_names)
    name = op_names[i]
    matrix = ops[i]
    @eval ITensors.op(::@OpName_str($name), ::SiteType"Ququart") = $matrix
end

Haven’t tried it, but it should definitely be doable with something along those lines. You basically never want to be evaluating strings.

3 Likes