繁体   English   中英

骆驼列表到树

[英]Ocaml list to tree

我想编写一个函数load: 'a option list -> 'a tree ,它从给定列表中恢复二叉树,该列表包含后缀顺序的元素。 如果列表不代表任何树,则您的函数应引发异常Load(必须提前声明)。

该树定义为:

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

到目前为止,我所做的是:

exception Load ;;

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

这是一个输入列表的示例:

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

怎么做有点棘手。 由于列表按后缀顺序排列,所以我想知道使用List.foldright函数是否会更好?

我认为您应该更努力地做功课(肯定有一些有趣的东西要学习),但是您显然不在乎:

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"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM