I’ve a task to write a function with type ‘a btree -> ‘a option list that stores the given tree in a list of elements of type ‘a option in postfix order (postorder).
Internal nodes will be represented by None, external nodes (leaves) with value x will be represented by Some x.
So far it’s easy to do for leaves, but how to put it in an 'a option list?
type 'a btree = L of 'a | N of 'a btree * 'a btree ;;
let rec store t =
match t with
| L x -> Some x
| N (a,b) -> None ???
;;
The second match case I know is incorrect, but how to solve it?
If you look at your first case, you’ll see it’s also not quite there; it’s returning
'a option, but you want the function to return an'a option list.Clearly you’ll be returning a list, so fix that first:
Now let’s fix the second case; we want to append
Noneto our output, but before that, we want the nodes of our subtrees:@has the typei.e. it joins lists together. We want to join the list of results from the left subtree, then the right, and then finally the result for this internal node.