[英]Ocaml list to tree
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. 我想编写一个函数
load: 'a option list -> 'a tree
,它从给定列表中恢复二叉树,该列表包含后缀顺序的元素。 If the list does not represent any tree, your function should raise the exception Load (you have to declare it earlier). 如果列表不代表任何树,则您的函数应引发异常Load(必须提前声明)。
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 ?? 由于列表按后缀顺序排列,所以我想知道使用
List.foldright
函数是否会更好?
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"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.