Skip to content

Commit 880daf4

Browse files
committed
Implement == and hash for IndexLens and ComposedLens
1 parent 3ce508d commit 880daf4

File tree

2 files changed

+29
-1
lines changed

2 files changed

+29
-1
lines changed

src/lens.jl

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ export setproperties
66
export constructorof
77

88

9-
import Base: get
9+
import Base: get, hash, ==
1010
using Base: getproperty
1111

1212
"""
@@ -99,6 +99,7 @@ struct IdentityLens <: Lens end
9999
get(obj, ::IdentityLens) = obj
100100
set(obj, ::IdentityLens, val) = val
101101

102+
102103
struct PropertyLens{fieldname} <: Lens end
103104

104105
function get(obj, l::PropertyLens{field}) where {field}
@@ -115,6 +116,11 @@ struct ComposedLens{LO, LI} <: Lens
115116
inner::LI
116117
end
117118

119+
function ==(l1::ComposedLens{LO, LI}, l2::ComposedLens{LO, LI}) where {LO, LI}
120+
return l1.outer == l2.outer && l1.inner == l2.inner
121+
end
122+
hash(l::ComposedLens, h::UInt) = hash(l.outer, hash(l.inner, hash(:ComposedLens, h)))
123+
118124
"""
119125
compose([lens₁, [lens₂, [lens₃, ...]]])
120126
@@ -173,6 +179,8 @@ end
173179
struct IndexLens{I <: Tuple} <: Lens
174180
indices::I
175181
end
182+
==(l1::IndexLens{I}, l2::IndexLens{I}) where {I} = l1.indices == l2.indices
183+
hash(l::IndexLens, h::UInt) = hash(l.indices, hash(:IndexLens, h))
176184

177185
Base.@propagate_inbounds function get(obj, l::IndexLens)
178186
getindex(obj, l.indices...)

test/test_core.jl

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -205,6 +205,26 @@ end
205205
end
206206
end
207207

208+
@testset "equality & hashing" begin
209+
# singletons (identity and property lens) are object equal
210+
for (l, r) [
211+
@lens(_) => @lens(_),
212+
@lens(_.a) => @lens(_.a)
213+
]
214+
@test l === r
215+
end
216+
217+
# composite and index lenses are structurally equal
218+
for (l, r) [
219+
@lens(_[1]) => @lens(_[1])
220+
@lens(_.a[2]) => @lens(_.a[2])
221+
]
222+
@test l == r
223+
@test hash(l) == hash(r)
224+
end
225+
end
226+
227+
208228
@testset "type stability" begin
209229
o1 = 2
210230
o22 = 2

0 commit comments

Comments
 (0)