[Haskell-cafe] Infinite loop?

rgo rgo at mail.interzet.ru
Fri Feb 17 18:08:17 EST 2006


On Fri, 17 Feb 2006 17:19:53 +0000
Jon Fairbairn <jon.fairbairn at cl.cam.ac.uk> wrote:

> On 2006-02-17 at 20:12GMT rgo wrote:
> > Hi all,
> > my program probably goes into infinite loop... But i cannot understand where and why.
> 
> getDirectoryContents will include "." and "..", so if you
> follow those, you're bound to loop.
> 
> -- 
> Jón Fairbairn                              Jon.Fairbairn at cl.cam.ac.uk
> 
> 

Thanks.
It's the third time in my life when do this error. :-[

here working code:

import System.Directory

data MyFile = MyDir {
                dir_name :: FilePath,
                dir_files :: [MyFile]
        }
        | MyFile {
                file_name :: FilePath
        }

read_dir_entries :: FilePath -> [FilePath] -> IO [MyFile]
read_dir_entries _ [] = return []
read_dir_entries dirname (name:names) = do
        isdir <- doesDirectoryExist name;
        entry <- if (isdir && (name /= ".") && (name /= ".."))
                        then read_dir (dirname ++ "/" ++ name)
                        else return (MyFile {file_name = name});
        entries <- read_dir_entries dirname names;
        return (entry:entries)

read_dir :: FilePath -> IO MyFile
read_dir name = do 
        content <- getDirectoryContents name;
        files <- read_dir_entries name content;
        return MyDir {
                dir_name = name,
                dir_files = files
        }

instance Show MyFile where
        show (MyDir {dir_name = name, dir_files = files}) = 
                "\n" ++ name ++ ":\n" ++ show files
        show (MyFile {file_name = name}) = "\t" ++ name ++ "\n"

main = do
        cwd <- getCurrentDirectory;
        dir <- read_dir cwd;
        print dir;


More information about the Haskell-Cafe mailing list