我正在研究一些使用树木的程序.我想知道是否有任何代码可以在OCaml中绘制一般树.
type Tree = Node of Tree * int * Tree | Child of int;;
Run Code Online (Sandbox Code Playgroud)
我在互联网上找到的只使用Caml Light,而不是Objective Caml.
提前致谢.
gas*_*che 12
你能用"画画"来澄清你的意思吗?我假设您正在考虑树的图形可视化?
我在使用工具graphviz使用的点格式生成图形/树形描述方面有相当不错的经验.我们的想法是你的OCaml程序以这种格式生成图形的文本表示,然后使用外部工具渲染它(将其转换为图像),并可能在屏幕上显示它.
Dot适用于一般图形.虽然您可能会发现具有更多功能的二叉树专用工具,但根据我的经验,它可以很好地适用于所有类型的树并显示通常您喜欢的内容.现在该工具并非没有缺陷,dot在某些情况下我遇到了bug(称为段错误).我仍然认为这是一个合理的选择.
dot具体如何输出格式:选择已有图形的任何一个例子,结构都很明显:它只是一种文本格式.然后你编写代码在图形结构上运行,Printf用正确的东西调用标签等等,然后瞧.例如,这个例子看起来很好,这里是源格式.我引用相关部分:
/* courtesy Ian Darwin and Geoff Collyer, Softquad Inc. */
digraph unix {
size="6,6";
node [color=lightblue2, style=filled];
"5th Edition" -> "6th Edition";
"5th Edition" -> "PWB 1.0";
"6th Edition" -> "LSX";
"6th Edition" -> "Interdata";
"Interdata" -> "Unix/TS 3.0";
"Interdata" -> "PWB 2.0";
"Interdata" -> "7th Edition";
"7th Edition" -> "8th Edition";
"7th Edition" -> "32V";
"7th Edition" -> "V7M";
"V7M" -> "Ultrix-11";
"8th Edition" -> "9th Edition";
[...]
}
Run Code Online (Sandbox Code Playgroud)
Fab*_*ant 10
Graphics如果它简单而不是太深,使用库来绘制树通常非常容易和有趣.
如果你想要一个文字表示:
type tree = Node of tree * int * tree | Child of int;;
let draw tree =
let rec print indent tree =
match tree with
Child n ->
Printf.printf "%s%d\n" indent n
| Node (left, n, right) ->
Printf.printf "%s----\n" indent;
print (indent ^ "| ") left;
Printf.printf "%s%d\n" indent n;
print (indent ^ "| ") right;
Printf.printf "%s----\n" indent
in
print "" tree
Run Code Online (Sandbox Code Playgroud)