I am trying to use SArrays in my project. I have tons of vectors and matrices that, in some cases, I need to modify only one index. What I am doing is to replace:
Trw[i] = T(0)
to
Trw = setindex(Trw, 0, i)
But it is somewhat strange. I am wondering if it is possible to overload setindex! or create a macro to make things easier.
I tried somethings without much success. Can anyone help me?
I wouldn’t recommend overloading setindex!, as it won’t have the expected behavior of mutating the object, but will instead just be replacing it. Also, overloading a function you don’t own (Base.setindex!) on a type you don’t own (SArray) is type-piracy and is not recommended because it can silently change the behavior other people’s code.
On the other hand, a macro seems totally reasonable. You’re trying to turn this expression:
julia> dump(:(Trw[i] = 0))
Expr
head: Symbol =
args: Array{Any}((2,))
1: Expr
head: Symbol ref
args: Array{Any}((2,))
1: Symbol Trw
2: Symbol i
2: Int64 0
into this one:
julia> dump(:(Trw = setindex(Trw, 0, i)))
Expr
head: Symbol =
args: Array{Any}((2,))
1: Symbol Trw
2: Expr
head: Symbol call
args: Array{Any}((4,))
1: Symbol setindex
2: Symbol Trw
3: Int64 0
4: Symbol i