Skip to content

Commit

Permalink
Avoid dependency on AutoHashEquals 0.2.
Browse files Browse the repository at this point in the history
  • Loading branch information
ztangent committed Oct 19, 2023
1 parent dc207bf commit 81ce391
Showing 1 changed file with 38 additions and 5 deletions.
43 changes: 38 additions & 5 deletions src/utils.jl
Original file line number Diff line number Diff line change
Expand Up @@ -12,24 +12,57 @@ lazy_collect(collection::Array) = collection
lazy_collect(element_type::Type, collection) = collect(element_type, collection)
lazy_collect(::Type{T}, collection::Array{T}) where {T} = collection

"Automatically generate `Base.hash` for a user-defined (composite) type."
"Generate `Base.hash` for a user-defined (composite) type."
macro auto_hash(type)
expr = quote
names = fieldnames($(esc(type)))
eval(AutoHashEquals.auto_hash($(esc(type)), names))
fields = fieldnames($(esc(type)))
eval(auto_hash_expr($(esc(type)), fields))
end
return expr
end

"Automatically generate `Base.(==)` for a user-defined (composite) type."
function auto_hash_expr(type, fields)
function expand(i)
if i == 0
:(h)
else
:(hash(a.$(fields[i]), $(expand(i-1))))
end
end
return quote
function Base.hash(a::$(type), h::UInt)
$(expand(length(fields)))
end
end
end

"Generate `Base.(==)` and `Base.isqual` for a user-defined (composite) type."
macro auto_equals(type)
expr = quote
names = fieldnames($(esc(type)))
eval(AutoHashEquals.auto_equals($(esc(type)), names))
eval(auto_equals_expr($(esc(type)), names))
end
return expr
end

function auto_equals_expr(type, fields)
function expand(i, f)
if i == 0
:true
else
:($f(a.$(fields[i]), b.$(fields[i])) && $(expand(i-1, f)))
end
end
return quote
function Base.:(==)(a::$(type), b::$(type))
$(expand(length(fields), :(==)))
end
function Base.isequal(a::$(type), b::$(type))
$(expand(length(fields), :isequal))
end
end
end

"Convert vector of unnormalized scores to probabiities."
function softmax(scores)
if isempty(scores) return Float64[] end
Expand Down

0 comments on commit 81ce391

Please sign in to comment.