F#树叶以连续尾递归列出

时间:2018-11-10 12:43:48

标签: list f# tree tail-recursion

我有一棵有树枝和树叶的类型树。我想获取叶子值的列表。到目前为止,我只能统计分支机构。

我的树:

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

我的代码:

let getList (tr:float tr)=
    let rec toList tree acc =
        match tree with
        | Leaf _ -> acc 0
        | Branch (tl,tr) -> toList tl (fun vl -> toList tr (fun vr -> acc(vl+vr+1)))
    toList tr id     

输入:

 let test=Branch (Leaf 1.2, Branch(Leaf 1.2, Branch(Branch(Leaf 4.5, Leaf 6.6), Leaf 5.4)))
 getList test

因此,我想获得一个列表:

[1.2; 1.2; 4.5; 6.6; 5.4]

我尝试了一些与此类似的变体,但没有成功。

  | Branch (tl,tr) -> toList tl (fun vl -> toList tr (fun vr -> (vl::vr)::acc))
    toList tr [] 

任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:3)

这是由于您的延续函数(acc)的签名是(int->'a) 如果要获取展平列表,则延续功能签名应为('a list->'b)

let getList tree =
    let rec toList tree cont =
        match tree with
        | Leaf a -> cont [a]
        | Branch (left, right) -> 
            toList left (fun l -> 
                toList right (fun r -> 
                    cont (l @ r)))
    toList tree id

编辑;这应该更有效

let getList tree = 
    let rec toList tree cont acc =
        match tree with 
        | Leaf a               -> cont (a :: acc)
        | Branch (left, right) -> toList left (toList right cont) acc
    toList tree id [] |> List.rev

答案 1 :(得分:3)

请注意,您的树类型不能代表只有一个子节点的节点。类型应为:

type Tree<'T> =
    | Leaf of 'T
    | OnlyOne of Tree<'T>
    | Both of Tree<'T> * Tree<'T>

要在连续中使用尾递归,请使用 continuation函数,而不是 acc 累加器:

let leaves tree =
    let rec collect tree cont =
        match tree with
        | Leaf x -> cont [x]
        | OnlyOne tree -> collect tree cont
        | Both (leftTree, rightTree) ->
            collect leftTree (fun leftAcc ->
                collect rightTree (fun rightAcc ->
                    leftAcc @ rightAcc |> cont))
    collect tree id

P / S:您的命名不是很好:tr含义太多。