Ocaml list to tree

2019-07-31 10:00发布

问题:

I want to write a function load: 'a option list -> 'a tree, that restores binary tree from the given list, which contains the elements in postfix order. If the list does not represent any tree, your function should raise the exception Load (you have to declare it earlier).

The tree is defined as :

type ‘a btree = L of ‘a | N of ‘a btree * ‘a btree

So far what I did was :

exception Load ;;

let rec load l =
    match l with
        | [] -> raise Load
        | Some x::_ -> L x
        | None::t -> N(?,load t)
;; 

Here's an example of an Input list:

[Some 2; Some 0; None; Some 5; Some 9; Some 20; None; None; None]

It's kind of tricky how to do it. Since the list is in postfix order, I'm wondering if it will be better to use List.foldright function ??

回答1:

I think you should try harder to do your homework (surely there is something interesting to learn), but as you apparently don't care:

let load input =
  let rec load stack = function
    | [] -> stack
    | Some elem :: rest -> load (L elem :: stack) rest
    | None :: rest ->
      match stack with
        | right :: left :: stack -> load (N(left, right) :: stack) rest
        | [] | [_] -> failwith "incorrect node arity"
  in
  match load [] input with
    | res :: [] -> res
    | [] -> failwith "no input"
    | _ :: _ :: _ -> failwith "remaining nodes"