Skip to content

Commit

Permalink
Apply hash consing to Term
Browse files Browse the repository at this point in the history
  • Loading branch information
Blablablanca committed Nov 11, 2024
1 parent a587847 commit b1cee9e
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 2 deletions.
7 changes: 5 additions & 2 deletions src/types.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
16 changes: 16 additions & 0 deletions test/hash_consing.jl
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using SymbolicUtils, Test
using SymbolicUtils: Term

struct Ctx1 end
struct Ctx2 end
Expand All @@ -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

0 comments on commit b1cee9e

Please sign in to comment.