Skip to content

Commit 8204e1b

Browse files
committed
Add apply! function to allow in-place application of queries
1 parent 01ad01a commit 8204e1b

3 files changed

Lines changed: 41 additions & 1 deletion

File tree

src/PlantGraphs.jl

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
module PlantGraphs
22

33
# Public API of PlantGraph
4-
export Node, Context, Graph, Rule, Query, rewrite!, apply, data, rules, graph,
4+
export Node, Context, Graph, Rule, Query, rewrite!, apply, apply!, data, rules, graph,
55
static_graph, data, graph_data,
66
has_parent, has_ancestor, ancestor, is_root, get_root, has_children, has_descendant,
77
children, get_descendant, is_leaf, traverse, traverse_dfs, traverse_bfs, draw,

src/Query.jl

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,3 +96,38 @@ function apply(g::Graph, query::Query{N, Q})::Vector{N} where {Q, N}
9696
end
9797
return output
9898
end
99+
100+
101+
"""
102+
apply!(output, g::Graph, query::Query)
103+
104+
Fill an array `output` with all the nodes in the graph that match the query supplied by
105+
the user.
106+
107+
# Examples
108+
```jldoctest
109+
julia> struct A <: Node end;
110+
111+
julia> struct B <: Node end;
112+
113+
julia> axiom = A() + B();
114+
115+
julia> g = Graph(axiom = axiom);
116+
117+
julia> output = A[];
118+
119+
julia> query = Query(A);
120+
121+
julia> apply!(output, g, query);
122+
```
123+
"""
124+
function apply!(output, g::Graph, query::Query{N, Q})::Vector{N} where {Q, N}
125+
!has_nodetype(static_graph(g), N) && (return N[])
126+
candidates = nodetypes(g)[N]
127+
for id in candidates
128+
if query.query(Context(g, g[id]))
129+
push!(output, g[id].data::N)
130+
end
131+
end
132+
return output
133+
end

test/api/test_graph_4.jl

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,4 +39,9 @@ let
3939
@test apply(pop, Query(GT.ACell))[1].state == 3
4040
@test apply(pop, Query(GT.CCell))[1].state == 1
4141
@test apply(pop, Query(GT.BCell))[1].state == 2
42+
43+
# Test in-place apply
44+
output = GT.ACell[]
45+
apply!(output, pop, Query(GT.ACell))
46+
@test output[1].state == 3
4247
end

0 commit comments

Comments
 (0)