In the spirit of keeping code clean and terse I think it would be great to be able to implicitly use (reference) a ‘special’ member of a struct. My apologies if this is already an existing feature that I have overlooked (don’t think so though).
Consider an example. Let’s say I have something like this:
mutable struct Layer
layer::Array{Int64,2}
res::Array{Int64,2}
back::Function
forward::Function
end
Then, within functions using Layers you might find a few references to the various members but many references to:
# Assume 'layers' is a previously defined 'Vector' of 'Layer'
layers[ x ].layer # long clunky reference
# let's shorten it...
l = layers # line needlessly wasted just to shorten expression
l[ x ].layer # Still ugly ...who knows how many times this will be repeated throughout our code
Sure, the later is better than the first but can we do better?
I don’t want to get in to recommending any specifics on the syntax but …What if I could omit .layer for all references? I think it would be very convenient to make that member anonymous. Other members would have to be specified in the normal way.
What it might look like in practice:
mutable struct Layer
Array{Int64,2} # To specify we want anonymous/implicit data of this type
res::Array{Int64,2}
back::Function
forward::Function
end
# Create Layer()
julia> layer = Layer(d, σ, δ) # We are obviously not assigning to an anonymous member ..we are creating the struct
julia> layer = [ 1 2 3; 4 5 6; 7 8 9] # Assign data to the (now existing) anonymous member of layer
julia> layer[1,2] # access data
2
One might expect the criticism that anonymous members make the code less clear but I would instead argue that it avoids redundancy. Notice that layers[x] is a layer and then we add a dot and say layer again!?! This seems to be quite common. Another way I’ve seen this issue in code in the wild is with member names such as data. Well, yes! …of course it’s data! It’s all data, so why use that word? The obvious answer is that generally most languages require every member to have a name. But why should it have to have a name if it is given one on creation? That is where redundancy is generated.
As an example I’ve seen things similar this:
mutable struct MyFileFormat
data::Array{Int64,2} # To specify we want anonymous/implicit data of this type
length # other arbitrary pieces of data
...
end
MyFile = MyFileFormat( ... )
# Since the data is the whole point of this. The data is the file!
# why should I have to redundantly specify it?
MyFile.data[ ] # Not pretty :(
MyFile[ ] # Better :)
I’m looking forward to hearing peoples’ thoughts this idea to see if it’s feasable.
cheers!