Can't follow foldTree example in Chapter 9

42 views
Skip to first unread message

Chip Grandits

unread,
Mar 23, 2009, 9:54:59 PM3/23/09
to Real World Haskell Book Club
I have been struggling quite a bit with Chapter 9.
Unfortunately I don't really know how to debug or trace so I can get
stopped dead pretty easily.

I am just trying to understand the code given in the book.

On page 230 foldTree is defined, on page 231 the countDirectories
iterator function is defined.

It seems to me from both looking at the code and reading the
explanation of the code that
foldTree countDirectories 0 somePath
should count all the directories in somePath AND keep recursing.

Yet when I load FoldDir into ghci, and try it, the above function only
returns a count of directories in somePath but does NOT recurse into
subdirectories.

(Note: in order to load FoldDir.hs from O'Reilly site, I had to
comment out the secondTake function, otherwise I get an error about
takeBaseName being undefined, but I don't see any reference to that
function anyway)

It seems like foldTree is designed to recurse into subdirectories and
countDirectories only ever returns Continue, so I'm just lost.

Any help is greatly appreciated.
-Chip

Chris G

unread,
Mar 26, 2009, 9:04:37 PM3/26/09
to real-world-has...@googlegroups.com
Ya, that code doesn't work.  The reason is because path' is not correct past the first level.
The line "let path' = path </> name " is the crux of the bug, because 'path' never changes!

To fix it, I added an extra argument to 'fold' that keeps track of the current subpath:
http://haskell.pastebin.com/mc9a9c8f

<     fold seed subpath = getUsefulContents subpath >>= walk seed
---
>     fold seed subpath = getUsefulContents subpath >>= walk subpath seed
25,26c25,26
<     walk seed (name:names) = do
<       let path' = path </> name
---
>     walk dir seed (name:names) = do
>       let path' = dir </> name
30c30
<         Skip seed'    -> walk seed' names
---
>         Skip seed'    -> walk path' seed' names
33a34
>               next <- fold seed' path'
36,38c37,39
<                 seed''        -> walk (unwrap seed'') names
<           | otherwise -> walk seed' names
<     walk seed _ = return (Continue seed)
---
>                 seed''        -> walk path' (unwrap seed'') names
>           | otherwise -> walk path' seed' names
>     walk _ seed _ = return (Continue seed)

btw: Debug.Trace is your friend.

Chris
Reply all
Reply to author
Forward
0 new messages