I am trying to understand a function of a code that i have, and there are some functions that i cannot explain , this is the function:
Julia
function op_mat(op)
op = op[:as_poly](domain="C")
op_a = op.x[:gens]
nab = op[:length]()
op_ab = ones(SymPy.Sym, nab)
coef = zeros(Complex, nab)
mat = zeros(Int64, length(op_a), nab)
for (i, (ps, c)) in enumerate(op[:as_dict]())
for (j, p) in enumerate(ps)
mat[j, i] = p
op_ab[i] = op_a[j]^p * op_ab[i]
end
coef[i] = c
end
return op_a, op_ab, mat, coef
end
what i’m having problem with is that [:as_poly](domain="C")
and op_a = op.x[:gens]
also (op[:as_dict]()
now for this one it could be converting op
to a dictionary but i’m not sure.
My understanding is that all a[b]
really does is call getindex(a, b) and return the result. So it would appear that the module defined getindex for the type of op. Something like (my return functions are totally made up, and I’m guessing at op’s type):
function Base.getIndex(x::Op, i::Symbol)::Function
if i == :as_poly
return (;domain::String = "") -> Poly(x, domain)
elseif i == :gens
return () -> Gens(x.y, x.z)
elseif i == :length
return () -> length(x.f)
end
return () -> nothing
end
An alternative would be if op had a map of symbols to functions it could be returning.
So really (at a guess) it’s just using getindex to create functions that can pull data from that op instance object when those functions are called, which makes me think they are going for sort of “object oriented” feel. It might also be returning functions rather than the values themselves to avoid the whole returns of different type overhead…
2 Likes