[英]F# How to Flatten a Binary Search Tree
I have a tree, structured as : 我有一棵树,结构如下:
type 'a Tree =| Leaf of 'a| Branch of 'a Tree * 'a Tree
I am using continuation-passing style tail recursion over my tree and trying to flatten it. 我在树上使用延续传递样式的尾递归并尝试将其展平。
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)))
This returns only [1.0] 这只返回[1.0]
However I only get the first leaf in a tree, my function does not work on an entire tree. 但是我只获得树中的第一片叶子,我的功能不适用于整棵树。 How can I achieve that? 我怎样才能做到这一点?
You're passing in a continuation, but you're not calling it anywhere. 你是在继续传递,但你不是在任何地方调用它。 Try this: 试试这个:
let rec loop tree k acc =
match tree with
| Leaf v -> k (v :: acc)
| Branch (tl,tr) -> loop tl (loop tr k) acc
Then loop xs id []
produces [4.0; 3.0; 2.0; 1.0]
然后loop xs id []
产生[4.0; 3.0; 2.0; 1.0]
[4.0; 3.0; 2.0; 1.0]
[4.0; 3.0; 2.0; 1.0]
. [4.0; 3.0; 2.0; 1.0]
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.