F# tree leaves to list with continuation tail-recursion

Viewed 284

I have a type tree which has branches and leaves. I would like to get a list of leaves values. So far I'm only able to count the branches.

My tree:

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

And my code:

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     

Input:

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

As a result, I would like to get a list:

[1.2; 1.2; 4.5; 6.6; 5.4]

I've tried some variations similar to this but with no success.

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

Any help would be appreciated.

2 Answers

This is due to your continuation function (acc) whose signature is (int -> 'a) If you want to get a flatten list the contination function signature should be ('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

Edit; this should be more efficient

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

Notice that your tree type cannot represent a node with only one child node. The type should be:

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

To use tail-recursion with continuation, please use a continuation function, not an accumulator:

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: your naming is not very good: tr has too many meanings.

Related