I have a hobby project which is about creating a tree to store identification numbers. I had used digit, stored at node, that is node can be 0 1 2 3 4 5 6 7 8 9.
After I have create tree, I want compose list from tree. But, I could not find a algorithm to manage my goal.
What I want :
"recompose tree" will return list of numbers. For below tree it should be
[ 2, 21, 243, 245, 246, 78, 789 ]
Root
/ \
2* 7
/ \ \
1* 4 8*
/ \ \ \
3* 5* 6* 9*
my data type : data ID x = ID ( ( x, Mark ), [ ID x ] )
data Mark = Marked | Unmarked
EDIT:
for convenience : * shows it is marked
I have stored digit as char, actually not 1,
it is stored as'1'
Do you have advice how I can do that ? ( advice is prefferred to be algorithm )
What about
?
That is, we traverse the tree while accumulating a value for the path from the root to a node. At every node we update the accumulator by multiplying the value for the path by 10 and adding the value for the node to it. The traversal produces a list of all accumulator values for marked node: so, at marked node we add the accumulator value to the list, for unmarked nodes we just propagate the list that we have collected for the children of the node.
How do we compute the list for the children of a node? We recursively call the traversal function (
go) to all children by mapping it over the list of children. That gives us a list of lists that we concatenate to obtain a single list. (concatMap f xsis justconcat (map f xs))orconcat . map f.)In attribute-grammar terminology: the accumulator serves as an inherited attribute, while the returned list is a synthesised attribute.
As a refinement, we can introduce an auxiliary function
isMarked,so that we can concisely write