Skip to content

Commit fec4552

Browse files
author
Alessandro Cheli
committed
sorted children
1 parent 7ccf2a2 commit fec4552

File tree

2 files changed

+32
-8
lines changed

2 files changed

+32
-8
lines changed

src/TermInterface.jl

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,10 +51,33 @@ export head
5151
"""
5252
children(x)
5353
Returns the children (aka tail) of the S-expression.
54+
55+
56+
Depending on the type and internal representation of `x`,
57+
`children(x)` may return an unsorted collection nondeterministically,
58+
This is to make sure to retrieve the children of an AST node when the order of children does not matter,
59+
but the speed of the operation does.
60+
To ensure to retrieve children in a sorted manner, you can use
61+
and implement the function `sorted_children`.
5462
"""
5563
function children end
5664
export children
5765

66+
"""
67+
sorted_children(x::T)
68+
69+
Returns the children of an AST node, in a **sorted fashion**.
70+
`isexpr(x)` must be true as a precondition. Analogous to `children`,
71+
but ensures that the operation is deterministic and always returns
72+
the children in the order they are stored.
73+
74+
By default, this redirects to `children`, therefore implementing
75+
it is optional.
76+
"""
77+
sorted_children(x) = children(x)
78+
export sorted_children
79+
80+
5881
"""
5982
operation(x)
6083

test/runtests.jl

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -23,24 +23,25 @@ end
2323

2424
@testset "Unsorted arguments" begin
2525
struct Sum
26-
d::Dict{Int, Any}
27-
Sum(xs...) = new(Dict{Int, Any}(xs...))
26+
d::Dict{Int,Any}
27+
Sum(xs...) = new(Dict{Int,Any}(xs...))
2828
end
2929

30-
TermInterface.isexpr(s::Sum) = true
30+
TermInterface.isexpr(s::Sum) = true
3131
TermInterface.head(::Sum) = (+)
3232
TermInterface.operation(s::Sum) = head(s)
33-
TermInterface.arguments(s::Sum) = [:($coeff * $val) for (coeff, val) in s.d]
34-
TermInterface.children(s::Sum) = sorted_arguments(s)
35-
TermInterface.sorted_arguments(s::Sum) = [:($coeff * $val) for (coeff, val) in sort!(collect(pairs(s.d)))]
33+
TermInterface.children(s::Sum) = [:($coeff * $val) for (coeff, val) in s.d]
34+
TermInterface.sorted_children(s::Sum) = [:($coeff * $val) for (coeff, val) in sort!(collect(pairs(s.d)))]
35+
TermInterface.arguments(s::Sum) = children(s)
36+
TermInterface.sorted_arguments(s::Sum) = sorted_children(s)
3637

3738
s = Sum(1 => :A, 2 => :B, 3 => :C)
3839
@test operation(s) == head(s) == (+)
3940
args = arguments(s)
4041
@test :(1A) in args
4142
@test :(2B) in args
4243
@test :(3C) in args
43-
44+
4445
@test sorted_arguments(s) == [:(1A), :(2B), :(3C)]
45-
@test children(s) == sorted_arguments(s)
46+
@test sorted_children(s) == sorted_arguments(s)
4647
end

0 commit comments

Comments
 (0)