Skip to content

Commit e0ef6f5

Browse files
committed
Convert traversing tree functions to iterators
It will yield in the specific order now
1 parent 81f1665 commit e0ef6f5

1 file changed

Lines changed: 20 additions & 38 deletions

File tree

ast_/tree.py

Lines changed: 20 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -98,47 +98,29 @@ def children(self, value):
9898
for x in value:
9999
self.children.append(x)
100100

101-
def inorder(self, funct, stopOn=None):
102-
""" Iterates in order, calling the function with the current node.
103-
If stopOn is set to True or False, it will stop on true or false.
101+
def inorder(self):
102+
""" Traverses the tree in order
104103
"""
105-
if stopOn is None:
106-
for i in self.children:
107-
i.inorder(funct)
108-
else:
109-
for i in self.children:
110-
if i.inorder(funct) == stopOn:
111-
return stopOn
112-
113-
return funct(self)
114-
115-
def preorder(self, funct, stopOn=None):
116-
""" Iterates in preorder, calling the function with the current node.
117-
If stopOn is set to True or False, it will stop on true or false.
104+
for i in self.children:
105+
yield from i.inorder()
106+
107+
yield self
108+
109+
def preorder(self):
110+
""" Traverses the tree in preorder
118111
"""
119-
if funct(self.symbol) == stopOn and stopOn is not None:
120-
return stopOn
121-
122-
if stopOn is None:
123-
for i in self.children:
124-
i.preorder(funct)
125-
else:
126-
for i in self.children:
127-
if i.preorder(funct) == stopOn:
128-
return stopOn
129-
130-
def postorder(self, funct, stopOn=None):
131-
""" Iterates in postorder, calling the function with the current node.
132-
If stopOn is set to True or False, it will stop on true or false.
112+
yield self
113+
114+
for i in self.children:
115+
yield from i.preorder()
116+
117+
def postorder(self):
118+
""" Traverses the tree in postorder
133119
"""
134-
if stopOn is None:
135-
for i in range(len(self.children) - 1, -1, -1):
136-
self.children[i].postorder(funct)
137-
else:
138-
for i in range(len(self.children) - 1, -1, -1):
139-
if self.children[i].postorder(funct) == stopOn:
140-
return stopOn
141-
return funct(self.symbol)
120+
for i in range(len(self.children) - 1, -1, -1):
121+
yield from self.children[i].postorder()
122+
123+
yield self
142124

143125
def appendChild(self, node):
144126
""" Appends the given node to the current children list

0 commit comments

Comments
 (0)