Skip to content

Instantly share code, notes, and snippets.

@aeshthetic
Created February 26, 2018 02:06
Show Gist options
  • Save aeshthetic/0a5d0ca4d219eecdfdedb10518040941 to your computer and use it in GitHub Desktop.
Save aeshthetic/0a5d0ca4d219eecdfdedb10518040941 to your computer and use it in GitHub Desktop.
type strTree =
St of int
| Leaf of string
| Tree of string * string * strTree list;;
let rec trees acc tree =
match tree with
| Tree (_, _, c) -> acc @ [tree] @ (List.fold_left (trees) [] c)
| _ -> acc;;
let rec stIfy pointer acc (trees: strTree list) =
match trees with
| [] -> acc
| [St num] -> acc @ [St num]
| [_] -> acc @ [St (pointer+1)]
| (St num) :: t -> stIfy (pointer+1) (acc @ [St num]) t
| _ :: t -> stIfy (pointer+1) (acc @ [St (pointer+1)]) t;;
let rec treeList (acc: (int * strTree) list) (trees: strTree list) =
let last x = x |> List.rev |> List.hd in
match trees with
| [Tree (a, b, c)] when List.length acc = 0 -> [(1, Tree (a, b, stIfy 1 [] c))]
| [Tree (a, b, c)] ->
let (pointer, _) = last acc in
acc @ [(pointer+1, Tree (a, b, stIfy pointer [] c))]
| Tree (a, b, c) :: t when List.length acc = 0 -> treeList (acc @ [(1, Tree (a, b, stIfy 1 [] c))]) t
| Tree (a, b, c) :: t ->
let (pointer, _) = last acc in
treeList (acc @ [(pointer+1, Tree (a, b, stIfy pointer [] c))]) t
| _ -> acc;;
let a1 = St 1
let a2 = Leaf "a"
let a3 = Tree("a","b",[])
let a4 = Tree("a","b",[a1])
let a5 = Tree("a","b",[a1;a4])
let a6 = Tree("a","b",[a5;a4])
let a7 = Tree("a","b",[a6;a4;a5]);;
let rec printTree = function
| St x -> "St " ^ (string_of_int x)
| Leaf x -> "Leaf " ^ x
| Tree (a, b, c) -> "Tree (" ^ a ^ ", " ^ b ^ ", [" ^ (c |> List.map printTree |> String.concat ", ") ^ "])";;
let rec printTreeList = function
| [] -> ""
| [(_, tree)] -> (printTree tree)
| (_, tree) :: t -> (printTree tree) ^ ", " ^ (printTreeList t);;
treeList [] (trees [] a6)
|> printTreeList
|> print_string;;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment