Pointwise getproperty

Hi,
I am thinking about the neatest way to neatest way to project an iterable of structs to an iterable of a member of each of these structs. For example:

struct Point
x::Int
y::Int
end
points=[Point(1,11),Point(2,12)]

#1.
xCoordinates=map(points) p do p.x end
#2.
xCoordinates=getproperty.(points,:x)
#3. (does not work)
xCoordinates=points..x
  1. & 2. work, but I do not find these syntaxes particularly beautiful. Is there a way to do it similarly to 3. that works?

The closest approximation would be:

x(p::Point) = p.x

xCoordinates = x.(points)

That’s pretty common in Julia code, since it’s common to provide public accessor functions for the (typically private) fields of a struct.

Of course, you can always define a macro:

julia> macro ..(a, b::Symbol)
         quote
           getproperty.($(esc(a)), $(QuoteNode(b)))
         end
       end
@.. (macro with 1 method)

julia> @.. points x
2-element Vector{Int64}:
 1
 2

But I’d still recommend just making the accessor function instead.

2 Likes