File tree Expand file tree Collapse file tree 2 files changed +32
-8
lines changed
Expand file tree Collapse file tree 2 files changed +32
-8
lines changed Original file line number Diff line number Diff line change @@ -51,10 +51,33 @@ export head
5151"""
5252 children(x)
5353Returns 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"""
5563function children end
5664export 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
Original file line number Diff line number Diff line change 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 :(1 A) in args
4142 @test :(2 B) in args
4243 @test :(3 C) in args
43-
44+
4445 @test sorted_arguments (s) == [:(1 A), :(2 B), :(3 C)]
45- @test children (s) == sorted_arguments (s)
46+ @test sorted_children (s) == sorted_arguments (s)
4647end
You can’t perform that action at this time.
0 commit comments