Skip to content

Commit 71896f9

Browse files
fix: implement isequal_with_metadata for custom symbolics
1 parent 69283c0 commit 71896f9

File tree

2 files changed

+56
-1
lines changed

2 files changed

+56
-1
lines changed

src/types.jl

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -314,6 +314,21 @@ function isequal_with_metadata(a::BasicSymbolic{T}, b::BasicSymbolic{S})::Bool w
314314
_isequal(a, b, E; comparator = isequal_with_metadata)::Bool && isequal_with_metadata(metadata(a), metadata(b)) || return false
315315
end
316316

317+
function isequal_with_metadata(a::Symbolic, b::Symbolic)::Bool
318+
a === b && return true
319+
typeof(a) == typeof(b) || return false
320+
321+
ma = metadata(a)
322+
mb = metadata(b)
323+
if iscall(a) && iscall(b)
324+
return isequal_with_metadata(operation(a), operation(b)) && isequal_with_metadata(arguments(a), arguments(b)) && isequal_with_metadata(ma, mb)
325+
elseif iscall(a) || iscall(b)
326+
return false
327+
else
328+
return isequal_with_metadata(ma, mb)
329+
end
330+
end
331+
317332
"""
318333
$(TYPEDSIGNATURES)
319334

test/hash_consing.jl

Lines changed: 41 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
using SymbolicUtils, Test
2-
using SymbolicUtils: Term, Add, Mul, Div, Pow, hash2, metadata
2+
using SymbolicUtils: Term, Add, Mul, Div, Pow, hash2, metadata, Symbolic, isequal_with_metadata
3+
import TermInterface
34

45
struct Ctx1 end
56
struct Ctx2 end
@@ -147,3 +148,42 @@ end
147148
@test ex2.hash2[] != h
148149
end
149150
end
151+
152+
struct MySymbolic <: Symbolic{Real}
153+
sym::BasicSymbolic{Real}
154+
end
155+
156+
TermInterface.iscall(x::MySymbolic) = iscall(x.sym)
157+
TermInterface.operation(x::MySymbolic) = operation(x.sym)
158+
TermInterface.arguments(x::MySymbolic) = arguments(x.sym)
159+
SymbolicUtils.metadata(x::MySymbolic) = metadata(x.sym)
160+
Base.isequal(a::MySymbolic, b::MySymbolic) = isequal(a.sym, b.sym)
161+
162+
@testset "`isequal_with_metadata` on custom symbolics" begin
163+
@syms x::Real
164+
xx = setmetadata(x, Int, 3)
165+
@test isequal(x, xx)
166+
@test !isequal_with_metadata(x, xx)
167+
myx = MySymbolic(x)
168+
myxx = MySymbolic(xx)
169+
@test isequal(myx, myxx)
170+
@test !isequal_with_metadata(myx, myxx)
171+
172+
ex = 2x
173+
exx = 2xx
174+
myex = MySymbolic(ex)
175+
myexx = MySymbolic(exx)
176+
@test isequal(ex, exx)
177+
@test !isequal_with_metadata(ex, exx)
178+
@test isequal(myex, myexx)
179+
@test !isequal_with_metadata(myex, myexx)
180+
181+
t = Term{Real}(max, Any[x, myex])
182+
tt = Term{Real}(max, Any[xx, myexx])
183+
@test isequal(t, tt)
184+
@test !isequal_with_metadata(t, tt)
185+
myt = MySymbolic(t)
186+
mytt = MySymbolic(tt)
187+
@test isequal(myt, mytt)
188+
@test !isequal_with_metadata(myt, mytt)
189+
end

0 commit comments

Comments
 (0)