Skip to content

Instantly share code, notes, and snippets.

@jbevain
Created October 26, 2010 15:14
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jbevain/647076 to your computer and use it in GitHub Desktop.
Save jbevain/647076 to your computer and use it in GitHub Desktop.
Node dumper using y combinator
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Node {
public string Text { get; private set; }
public IList<Node> Children { get; private set; }
public Node (string text, params Node [] children)
{
this.Text = text;
this.Children = children ?? new Node [0];
}
}
static class TreePrettyPrinter {
struct NodeTuple {
public readonly Node Node;
public readonly bool IsTail;
public readonly string Indent;
NodeTuple (Node node, bool is_tail, string indent)
{
this.Node = node;
this.IsTail = is_tail;
this.Indent = indent;
}
public static NodeTuple Create (Node node, bool is_tail, string indent)
{
return new NodeTuple (node, is_tail, indent);
}
}
static Func<A, R> Y<A, R> (Func<Func<A, R>, Func<A, R>> f)
{
Func<A, R> g = null;
g = f (a => g (a));
return g;
}
static string Print (Node node)
{
return Y<NodeTuple, string> (f => t =>
t.Node.Children
.Select (c =>
f (NodeTuple.Create (
c,
c == t.Node.Children [t.Node.Children.Count - 1],
t.Indent + (t.IsTail ? " " : "│ "))))
.Aggregate (
t.Indent + (t.IsTail ? "└─" : "├─") + t.Node.Text + Environment.NewLine,
string.Concat)
) (NodeTuple.Create (node, true, ""));
}
public static void Print (TextWriter writer, Node node)
{
writer.WriteLine (Print (node));
}
}
class Program {
static void Main ()
{
var node = new Node ("a",
new Node ("b",
new Node ("c",
new Node ("d")),
new Node ("e",
new Node ("f"))),
new Node ("g",
new Node ("h",
new Node ("i")),
new Node ("j"),
new Node ("k")));
TreePrettyPrinter.Print (Console.Out, node);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment