I have the following tree structure:
type 'a tree =
| Function of string * 'a tree list (* function name and arguments *)
| Terminal of 'a
I use this tree structure to construct an abstract syntax tree:
type atoms =
| Int of int
| Bool of bool
let t1 = Function ("+", [Function ("*", [Terminal (Int 5);
Terminal (Int 6)]);
Function ("sqrt", [Terminal (Int 3)])])
let t2 = Function ("-", [Terminal (Int 4); Terminal (Int 2)])
Tree representation of t1
:
Tree representation of t2
:
Goal: replace one of the subtrees in t1
with t2
at a specified t1
index position. The index position starts at 0 at the root node and is depth-first. In the figures above, I have labelled all the nodes with their index to show this.
For example, replace_subtree t1 4 t2
replaces the subtree at index 4 in t1
with t2
, resulting in this tree:
Function ("+", [Function ("*", [Terminal (Int 5);
Terminal (Int 6)]);
Function ("-", [Terminal (Int 4);
Terminal (Int 2)])])
This is essentially a crossover operation in tree-based genetic programming.
How do I implement replace_subtree
in OCaml?
I would strongly prefer a purely functional solution.
Note that this question is similar to How do I replace part of a tree with another tree at the specified index?, except that the programming language in this question is OCaml instead of Scheme/Racket. I have some trouble understanding Scheme/Racket, so I am looking for an OCaml solution.