Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

any possible to vectorize getproperty as arr..name? #50180

Closed
ctarn opened this issue Jun 15, 2023 · 3 comments
Closed

any possible to vectorize getproperty as arr..name? #50180

ctarn opened this issue Jun 15, 2023 · 3 comments

Comments

@ctarn
Copy link
Contributor

ctarn commented Jun 15, 2023

In practice, I often need to extract the same property of each item of an array, and generate a property array.
To get the name property of an item, we can simply call x.name. It should be equal to getproperty(x, :name).

Given the array A, currently I have to call getproperty.(A, :name) to generate the array of property name. (or, something like [x.name for x in A])

This function is very frequently used, and thus the code can be very verbose, comparing between x.name and getproperty.(A, :name).

I want a syntax like A..name to vectorize the process. I have tried the following method.

..(value, name::Symbol) = getproperty.(value, name)

which enables the following usage:

julia> A = [(a=1, b=2), (a=3, b=4)]
2-element Vector{NamedTuple{(:a, :b), Tuple{Int64, Int64}}}:
 (a = 1, b = 2)
 (a = 3, b = 4)

julia> ..(A, :a)
2-element Vector{Int64}:
 1
 3

julia> A..:a
2-element Vector{Int64}:
 1
 3

However, A..a would raise UndefVarError error.

julia> A..a
ERROR: UndefVarError: `a` not defined

That is, the : can not be omitted unlike x.name.

May I ask if there is any possibility to solve it, or any other concise method to implement the feature?

Thank you very much!

@Zentrik
Copy link
Member

Zentrik commented Jun 15, 2023

If you're primarily working with property arrays you might want to check out StructArrays.jl

@chrstphrbrns
Copy link
Contributor

#22710

@ctarn
Copy link
Contributor Author

ctarn commented Jun 15, 2023

Thanks for your help. I have read the previous discussion. I heard StructArray before but haven't tried it. Closing the issue.

@ctarn ctarn closed this as completed Jun 15, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants