[Haskell-cafe] Re: Filesystem questions

apfelmus apfelmus at quantentunnel.de
Sun Oct 14 07:26:01 EDT 2007


Yitzchak Gale wrote:
> I wrote:
>>>> ...a tool for recursing through directories...
>>>> How about a built-in function that represents a directory tree
>>>> as a lazy Data.Tree?
> 
> Bryan O'Sullivan wrote:
>>> See System.FilePath.Find in
>>> http://hackage.haskell.org/cgi-bin/hackage-scripts/package/FileManip-0.2
> 
>> -- List all directories in the tree rooted at the given path
>> traverseDirectories :: MonadIO m =>
>>   TraversalDirection -> FilePath -> ListT m Directory
>>
>> You could plug the above into your machinery for
>> "recursion predicates" and all the other nice stuff.
> 
> Or - getting back to the "lazy Data.Tree" idea -
> we could define TreeT, analgous to ListT:
> 
> newtype TreeT m a = NodeT (m (a, TreeT (ListT m) a))
> 
> and give it a nice Monad instance. Then you can prune
> and filter trees in a natural way, inside the monad.

Eh, isn't that what ListT is already for? I mean,

   type Directory = FilePath

   contents :: MonadIO m => Directory -> m [FilePath]

   liftList :: Monad m => m [a] -> ListT m a
   runList  :: Monad m => ListT m a -> m [a]

allows you to prune the directory tree in whatever way you like it. 
Here's an example top-down traversal that lists all non-directories:

   allFiles :: MonadIO m => Directory -> m [FilePath]
   allFiles d = runList $ do
      f <- liftList $ contents d
      if isDirectory f
        then allFiles f
        else return f

In other words, ListT is like one of those iterators I keep hearing from 
the Python/Java/.../imperative world (except that you can't suspend a 
traversal once started).

Regards,
apfelmus



More information about the Haskell-Cafe mailing list