簡體   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