Skip to content

Commit

Permalink
Added impl for varname_and_value_leaves that can handle containers (T…
Browse files Browse the repository at this point in the history
…uringLang#674)

with multiple varnames typically used in the context of DPPL
  • Loading branch information
torfjelde authored Sep 30, 2024
1 parent 8c3aa44 commit 4c60c9f
Showing 1 changed file with 40 additions and 0 deletions.
40 changes: 40 additions & 0 deletions src/utils.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1028,6 +1028,46 @@ function varname_and_value_leaves(vn::VarName, x)
return Iterators.map(value, Iterators.flatten(varname_and_value_leaves_inner(vn, x)))
end

"""
varname_and_value_leaves(container)
Return an iterator over all varname-value pairs that are represented by `container`.
This is the same as [`varname_and_value_leaves(vn::VarName, x)`](@ref) but over a container
containing multiple varnames.
See also: [`varname_and_value_leaves(vn::VarName, x)`](@ref).
# Examples
```jldoctest varname-and-value-leaves-container
julia> using DynamicPPL: varname_and_value_leaves
julia> # With an `OrderedDict`
dict = OrderedDict(@varname(y) => 1, @varname(z) => [[2.0], [3.0]]);
julia> foreach(println, varname_and_value_leaves(dict))
(y, 1)
(z[1][1], 2.0)
(z[2][1], 3.0)
julia> # With a `NamedTuple`
nt = (y = 1, z = [[2.0], [3.0]]);
julia> foreach(println, varname_and_value_leaves(nt))
(y, 1)
(z[1][1], 2.0)
(z[2][1], 3.0)
```
"""
function varname_and_value_leaves(container::OrderedDict)
return Iterators.flatten(varname_and_value_leaves(k, v) for (k, v) in container)
end
function varname_and_value_leaves(container::NamedTuple)
return Iterators.flatten(
varname_and_value_leaves(VarName{k}(), v) for (k, v) in pairs(container)
)
end

"""
Leaf{T}
Expand Down

0 comments on commit 4c60c9f

Please sign in to comment.