【问题标题】:F# How to Flatten a Binary Search TreeF# 如何展平二叉搜索树
【发布时间】:2019-04-12 03:08:54
【问题描述】:

我有一棵树,结构如下:

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]

但是我只得到树的第一片叶子,我的函数不适用于整棵树。我怎样才能做到这一点?

【问题讨论】:

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


    【解决方案1】:

    你传递了一个延续,但你没有在任何地方调用它。试试这个:

    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]

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-18
      • 1970-01-01
      • 2016-06-05
      相关资源
      最近更新 更多