I am wondering why filter and filter! give different results in the example below. Case 1 with filter!
includes an extra element whereas Case 2 with filter
works as expected
mutable struct M
x::Int
y::Int
end
Case 1:
m1 = [M(i,i+1) for i in 1:4]
filter!(x->x == m1[2], m1)
Results:
println(m1)
M[M(2, 3), M(3, 4)]
Case 2:
m2 = [M(i,i+1) for i in 1:4]
m3 = filter(x->x == m2[2], m2)
Results:
julia> println(m3)
M[M(2, 3)]
I would guess in Case 1 what m1[2]
is changes as you mutate m1
with filter!
; in other words, each time you evaluate that anonymous function inside filter!
you could be getting a different object because the filter is changing the array.
2 Likes
Thanks. That was a silly mistake on my part. Using z = m1[2] fixes the problem.
I am trying to navigate several issues with tests of equality on mutable structs. Evidently, there is a long standing issue. Is there a recommended solution for testing that the fields in two structs are equal? Should I iterate over the fields and use getfield
to test the values?
1 Like