Visualize a tree: Difference between revisions

m
m (→‎Functional composition: Adjusted type comments (Node contents don't have to be strings))
Line 534:
`-- (null)</pre>
=={{header|Elena}}==
ELENA 3.4.x :
<lang elena>/// a program to produce a visual representation of some tree.
<lang elena>import system'routines.
 
import extensions.
<lang elena>import system'routines.;
import extensions.;
 
class Node
{
objectstring theValue.;
objectNode[] theChildren.;
constructor name :new(string value, Node[] children:children)
[{
theValue := value.;
theChildren := (children ?? Array min) toArray.;
]}
constructor name :new(string value)
<= name:new(value, children:nil.new Node[](0));
constructor new(Node[] children:children)
<= name:emptyLiteralnew(emptyString, children:children.);
get() = theValue.;
constructor name : value child:child
<= name:value children(Array single:child).
get = theValue.
childrenChildren = theChildren.;
}
 
extension treeOp
{
writeTree(node, prefix)
[{
var children := node children.Children;
var length := children length.Length;
children zip.zipForEach(RangeEnumeratornew from:Range(1, to:length), forEach(:child:,index)
[{
self .printLine(prefix,"|").;
self .printLine(prefix,"+---",child .get().);
var nodeLine := prefix + (index==length).iif(" ","| ").;
self .writeTree(child,nodeLine).;
].});
^ self.
]}
writeTree(node)
= self~treeOp .writeTree(node,"").;
}
 
public program()
{
[
var tree := Node children:.new(
(new Node[]{
Node name:.new("a", new children:Node[]
({
Node name:.new("b", child:(Nodenew name:Node[]{Node.new("c")}),
Node name:.new("d")
}),
Node name:.new("e")
}).;
console .writeTree(tree); readChar.readChar()
]}</lang>
{{out}}
<pre>
Anonymous user