Skip to content

Commit 4c60c9f

Browse files
authored
Added impl for varname_and_value_leaves that can handle containers (#674)
with multiple varnames typically used in the context of DPPL
1 parent 8c3aa44 commit 4c60c9f

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

src/utils.jl

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1028,6 +1028,46 @@ function varname_and_value_leaves(vn::VarName, x)
10281028
return Iterators.map(value, Iterators.flatten(varname_and_value_leaves_inner(vn, x)))
10291029
end
10301030

1031+
"""
1032+
varname_and_value_leaves(container)
1033+
1034+
Return an iterator over all varname-value pairs that are represented by `container`.
1035+
1036+
This is the same as [`varname_and_value_leaves(vn::VarName, x)`](@ref) but over a container
1037+
containing multiple varnames.
1038+
1039+
See also: [`varname_and_value_leaves(vn::VarName, x)`](@ref).
1040+
1041+
# Examples
1042+
```jldoctest varname-and-value-leaves-container
1043+
julia> using DynamicPPL: varname_and_value_leaves
1044+
1045+
julia> # With an `OrderedDict`
1046+
dict = OrderedDict(@varname(y) => 1, @varname(z) => [[2.0], [3.0]]);
1047+
1048+
julia> foreach(println, varname_and_value_leaves(dict))
1049+
(y, 1)
1050+
(z[1][1], 2.0)
1051+
(z[2][1], 3.0)
1052+
1053+
julia> # With a `NamedTuple`
1054+
nt = (y = 1, z = [[2.0], [3.0]]);
1055+
1056+
julia> foreach(println, varname_and_value_leaves(nt))
1057+
(y, 1)
1058+
(z[1][1], 2.0)
1059+
(z[2][1], 3.0)
1060+
```
1061+
"""
1062+
function varname_and_value_leaves(container::OrderedDict)
1063+
return Iterators.flatten(varname_and_value_leaves(k, v) for (k, v) in container)
1064+
end
1065+
function varname_and_value_leaves(container::NamedTuple)
1066+
return Iterators.flatten(
1067+
varname_and_value_leaves(VarName{k}(), v) for (k, v) in pairs(container)
1068+
)
1069+
end
1070+
10311071
"""
10321072
Leaf{T}
10331073

0 commit comments

Comments
 (0)