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.



Let's say you had a recursive function
dfsthat visited every node of a tree, with one parameter being the index number of the node.Now rewrite this function to return an additional value which is a copy of the subtree below the node. I.e, it visits the subtrees of the node recursively (receiving copies of the subtrees) and constructs a new node as their parent.
Now add two parameters to the function, the index and the desired replacement. When reaching the desired index, the function returns the replacement instead of the copy of the node.
(Since this looks like possible homework I don't want to provide code.)