English version
Accueil     À propos     Téléchargement     Ressources     Contactez-nous    

Ce site est rarement mis à jour. Pour les informations les plus récentes, rendez-vous sur le nouveau site OCaml à l'adresse ocaml.org.

Browse thread
[Caml-list] Stack Overflow... (recursion in try-statement)
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: 2002-04-23 (22:24)
From: Will Benton <willb@c...>
Subject: Re: [Caml-list] Stack Overflow... (recursion in try-statement)
On Tue, 2002-04-23 at 16:48, Oliver Bandel wrote:
> Hello,
> why does an stack overflow-error occur here?
> let rec traversedir dir =
>           try ( [Unix.readdir dir] @ traversedir dir ) with
>           End_of_file -> [];;
> I have not tried it with very deep directories, so
> I did not expect such an error...
> What is the problem here?

It looks to me like this will never terminate, since "traversedir dir"
calls "traversedir dir".

I don't have any O'Caml code to do what you want, but I do have some
pseudocode (OK, it's python) to perform a depth-first traversal of a
directory hierarchy, performing some action on every file that satisfies
some predicate:

def dirwalk(tree, predicate, action):
    for file in os.listdir(tree):
        fullpath = tree + "/" + file
        if os.path.isdir(fullpath) and not os.path.islink(fullpath):
            dirwalk(fullpath, predicate, action)
            if predicate(fullpath):

This could be transliterated into bad O'Caml trivially, and into
idiomatic O'Caml without too much work.  I'd do it for you, but I'm on
my way out of the office.  :-)

Notice that I ignore symbolic links.  This is necessary to avoid cycles,
since a UNIX filesystem is a directed graph and not a tree. 
(Alternatively, you could keep track of what canonical paths you've
visited and only descend down a tree that you haven't already marked.)


To unsubscribe, mail caml-list-request@inria.fr Archives: http://caml.inria.fr
Bug reports: http://caml.inria.fr/bin/caml-bugs FAQ: http://caml.inria.fr/FAQ/
Beginner's list: http://groups.yahoo.com/group/ocaml_beginners