I'm currently working on a problem where I have a tree structure composed
of:
type Node
value
label
children
end
which I want to traverse and have different functions called depending on
the value of label. Normally I would just sub-type Node. However, the
results are coming from a parser which allows the user to specify a myriad
of different types. Thus, 'label' depends on the particular parse rule
executed.
The traversal code would look something like:
function transform(fn, node)
cvalues = [transform(fn, child) for child in node.children]
return fn(node, cvalues, node.label)
end
The question is the how to get Julia to select the correct function to call
based on 'node.label'. For example, I might have something like:
htmlformat(node, children, label_is_x) = "<tag>"
htmlformat(node, children, label_is_y) = "</tag>"
Two methods I've come up with so far to do this are:
1. Use the PatternDispatch package
2. Automatically create types that can be used as labels for selecting
the proper function
I'm currently exploring the first choice (why re-invent the wheel?).
However, it seems like it might still be a more direct approach to generate
types as labels. For example, I could generate the types when generating
the grammars:
macro maketype(label)
quote
type $(esc(label)) end
end
end
which then could be used directly in the methods. Has anyone else tried
this approach before? Are there known potential issues? It seems like this
could be a nice general approach for a light-weight version of the
PatternDispatch.
Thanks!