hubFS: THE place for F#

. . . are you on The Hub?
Welcome to hubFS: THE place for F# Sign in | Join | Help
in Search

Expert F# - computing tree size with continuations

Last post 05-25-2008, 23:51 by MatteoT. 2 replies.
Sort Posts: Previous Next
  •  05-17-2008, 3:12 5940

    Expert F# - computing tree size with continuations

    Hi,

    first of all i would like to say that i really love F# and definetly enjoy reading this book.

    I had some starting problems understanding continuations,
    but now i think i found a little mistake that troubled my mind.

    In Listing 8-11 (p.205) the size of the tree is computed with continuations,
    but the count is only increased for Tips, but the Nodes contain content as well.
    If i now get it right, there should be added 1 to the result of the sub-trees in the computation.

    e.g. with a tree like:

    (*
             x
            / \
           /   \
          x     x
         / \   / \
        o   o o   o
    *)
    
    let tree = Node( "n1", Node("n2",Tip("t1"),Tip("t2")), Node("n3",Tip("t3"),Tip("t4")) )
    
    It computes a count of 4, wich is the count of Tips,
    but there are actually 7 values in the tree.
    Can someone confirm this, or else explain it to me please?
    thx
  •  05-17-2008, 5:11 5943 in reply to 5940

    Re: Expert F# - computing tree size with continuations

    That's exactly right. I guess its an exercise for the reader to update this to count the internal nodes as well. :-)

    Kind regards

    Don

  •  05-25-2008, 23:51 6010 in reply to 5943

    Re: Expert F# - computing tree size with continuations

    Here's the trivial "fix" to count all the internal nodes as well. Smile [:)]
    
     let rec sizeContAcc acc tree cont =
      match tree with
      | Tip _ -> cont (1+acc)
      | Node(_,treeLeft,treeRight) -> sizeContAcc (1+acc) treeLeft (fun accLeftSize -> 
                                      sizeContAcc accLeftSize treeRight cont)
    
    -Matteo
View as RSS news feed in XML
Powered by Community Server, by Telligent Systems