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

Use with mutable arrays? #18

Open
evanfields opened this issue Feb 27, 2021 · 4 comments
Open

Use with mutable arrays? #18

evanfields opened this issue Feb 27, 2021 · 4 comments

Comments

@evanfields
Copy link

If one has a mutable array of immutable objects, is it possible to use Accessors.jl to update just one object in the array without copying the whole array?

julia> struct MyT
       x::Int
       end

julia> v = [MyT(1), MyT(2)]
2-element Vector{MyT}:
 MyT(1)
 MyT(2)

julia> @set v[1].x = 5
2-element Vector{MyT}:
 MyT(5)
 MyT(2)

julia> v
2-element Vector{MyT}:
 MyT(1)
 MyT(2)

Looks like @set is returning a whole copy of v, not just updating v[1]. Is that right? Is there a way around this?

@jw3126
Copy link
Member

jw3126 commented Feb 28, 2021

Personally I usually do

v1 = v[1]
v[1] = @set v1.x = 5

Alternatives would be to use Persistent Arrays for efficient immutable updates of arrays. It should be easy to support FunctionalCollections with Accessors but it is not yet implemented I think. Or defining a custom lens that is allowed to do mutation. If you want to work on one of these, I am happy to help.

@evanfields
Copy link
Author

Thank you for the response and tip. Right now I'm working on some other personal projects so unfortunately it's unlikely I'll open a PR.

@jw3126
Copy link
Member

jw3126 commented Mar 4, 2021

Sure no problem!

@aplavin
Copy link
Collaborator

aplavin commented Apr 23, 2023

Try the view-lens now available in AccessorsExtra:

julia> @set v |> view(_, 1)[].x = 5
2-element Vector{MyT}:
 MyT(5)
 MyT(2)

julia> v
2-element Vector{MyT}:
 MyT(5)
 MyT(2)

Suggestions for a cleaner approach that doesn't introduce new structs (for the user to learn) are welcome!

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