From b1cee9eadde49705320710633d94d9920af3a14d Mon Sep 17 00:00:00 2001 From: Blanca Luo Date: Mon, 11 Nov 2024 13:10:21 -0500 Subject: [PATCH] Apply hash consing to `Term` --- src/types.jl | 7 +++++-- test/hash_consing.jl | 16 ++++++++++++++++ 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/src/types.jl b/src/types.jl index 8a8c7361..81220ebd 100644 --- a/src/types.jl +++ b/src/types.jl @@ -97,6 +97,7 @@ function ConstructionBase.setproperties(obj::BasicSymbolic{T}, patch::NamedTuple # Call outer constructor because hash consing cannot be applied in inner constructor @compactified obj::BasicSymbolic begin Sym => Sym{T}(nt_new.name; nt_new...) + Term => Term{T}(nt_new.f, nt_new.arguments; nt_new...) _ => Unityper.rt_constructor(obj){T}(;nt_new...) end end @@ -395,11 +396,13 @@ function Term{T}(f, args; kw...) where T args = convert(Vector{Any}, args) end - Term{T}(;f=f, arguments=args, hash=Ref(UInt(0)), kw...) + s = Term{T}(;f=f, arguments=args, hash=Ref(UInt(0)), kw...) + BasicSymbolic(s) end function Term(f, args; metadata=NO_METADATA) - Term{_promote_symtype(f, args)}(f, args, metadata=metadata) + s = Term{_promote_symtype(f, args)}(f, args, metadata=metadata) + BasicSymbolic(s) end function Add(::Type{T}, coeff, dict; metadata=NO_METADATA, kw...) where T diff --git a/test/hash_consing.jl b/test/hash_consing.jl index aaf97997..82385736 100644 --- a/test/hash_consing.jl +++ b/test/hash_consing.jl @@ -1,4 +1,5 @@ using SymbolicUtils, Test +using SymbolicUtils: Term struct Ctx1 end struct Ctx2 end @@ -24,3 +25,18 @@ struct Ctx2 end xm3 = setmetadata(x1, Ctx2, "meta_2") @test xm1 !== xm3 end + +@syms a b c + +@testset "Term" begin + t1 = sin(a) + t2 = sin(a) + @test t1 === t2 + t3 = Term(identity,[a]) + t4 = Term(identity,[a]) + @test t3 === t4 + t5 = Term{Int}(identity,[a]) + @test t3 !== t5 + tm1 = setmetadata(t1, Ctx1, "meta_1") + @test t1 !== tm1 +end