Version française
Home     About     Download     Resources     Contact us    
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: -- (:)
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)
        else:
            if predicate(fullpath):
                action(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.)




best,
wb

-------------------
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