OCaml+Graphviz 初练

用OCaml做解析

bst.ml:

Code
type 'a bst=Leaf|Node of 'a * 'a bst * 'a bst;;

let rec insert t x=match t with
    
|Leaf->Node (x,Leaf,Leaf)
    
|Node (y,l,r) when x<>y->if x<y then
        Node (y,insert l x,r)
        
else Node (y,l,insert r x)
    
|_->t;;

let rec build l=match l with
    
|[]->Leaf
    
|h::t->insert (build t) h;;

let rec inorder t=match t with
    
|Leaf->[]
    
|Node (x,l,r)->inorder l @ [x] @ inorder r;;
(* -------------------------------------------------- *)
let rec print_list l=match l with
    
|[]->()
    
|[x]->Printf.printf "%d\n" x
    
|h::t->Printf.printf "%d " h;print_list t;;

let rec aux_dot_output t=match t with
    
|Leaf->()
    
|Node (x,l,r)->
        Printf.printf 
"%d [label=\"{<x> %d|{<l>|<r>}} \"];\n" x x;
        Printf.printf 
"%d:l->%s;\n%d:r->%s;\n"
        x
        (
match l with
            
|Leaf->"Leaf"
            
|Node (y,_,_)->string_of_int y^":x")
        x
        (
match r with
            
|Leaf->"Leaf"
            
|Node (y,_,_)->string_of_int y^":x");
    aux_dot_output l;
    aux_dot_output r;;

let dot_output t=Printf.printf "digraph G{\nnode [shape=record];\n";
            aux_dot_output t;
            Printf.printf 
"}\n";;

这个是主程序:main.ml

Code
open Bst;;

let l=[4;1;0;8;9;7;2;5;3;6in
let t=build l in
(*print_list (inorder t);*)
dot_output t;;

输出的图如下:点击看大图

image

原文地址:https://www.cnblogs.com/euphoria/p/1492406.html