F#如何展平二进制搜索树

时间:2018-11-08 15:12:24

标签: recursion functional-programming f# tail-recursion continuation-passing

我有一棵树,结构为:

type 'a Tree =| Leaf of 'a| Branch of 'a Tree * 'a Tree

我正在对树使用连续传递样式的尾递归,并试图将其展平。

let rec loop tree k acc = 
  match tree with
  | Leaf v -> v :: acc
  | Branch (tl,tr) -> loop tl (loop tr k) acc
loop xs id []


(Branch (Branch (Leaf 1.0,Leaf 2.0),Branch (Leaf 3.0,Leaf 4.0)))

这仅返回[1.0]

但是,我只获得树中的第一片叶子,但是我的函数无法在整棵树上使用。我该如何实现?

1 个答案:

答案 0 :(得分:5)

您传递的是延续,但您没有在任何地方调用它。试试这个:

let rec loop tree k acc = 
  match tree with
  | Leaf v -> k (v :: acc)
  | Branch (tl,tr) -> loop tl (loop tr k) acc

然后loop xs id []产生[4.0; 3.0; 2.0; 1.0]