Ocaml-树预购/后购/订购

时间:2018-11-12 20:40:28

标签: tree ocaml preorder

我在OCaml中给出了树的定义

type 'a tree = Node of 'a * 'a tree list;;

let rec fold_tree f (Node (x,l)) =
f x (map (fold_tree f) l);;

有人可以帮我如何使用fold_tree编写例如preorder(无需其他递归)。我知道没有fold_tree怎么做,但这使我很麻烦

到目前为止,我已经知道了:

let preorder t =
  fold_tree (fun x l -> 
    (fold_left(fun acc h -> h@acc) x l ) ) t;;

但是ocaml将t视为树列表...

1 个答案:

答案 0 :(得分:0)

    OCaml version 4.02.3

# type 'a tree = Node of 'a * 'a tree list;;
type 'a tree = Node of 'a * 'a tree list
# let rec fold_tree f (Node (x,l)) =
  f x (List.map (fold_tree f) l);;
val fold_tree : ('a -> 'b list -> 'b) -> 'a tree -> 'b = <fun>
# let preorder t =
  fold_tree (fun x l -> 
    (List.fold_left(fun acc h -> h@acc) x l ) ) t;;
val preorder : 'a list tree -> 'a list = <fun>

您正在使用x作为List.fold_left的起始值并将其附加值。这使得x为'a list,因此t必须为'a list tree。将x更改为[x],您将得到:

# let preorder t =
  fold_tree (fun x l -> 
    (List.fold_left(fun acc h -> h@acc) [x] l ) ) t;;
val preorder : 'a tree -> 'a list = <fun>