Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I modified the older answer that Davorak linked to to use the new <code>pipes</code> library.</p> <p>It uses <code>StateP</code> to keep a queue of untraversed directories so that it can do a breadth first traversal. It uses <code>MaybeP</code> for exiting from the loop, as a convenience.</p> <pre><code>import Control.Monad import Control.Proxy import Control.Proxy.Trans.Maybe import Control.Proxy.Trans.State as S import Data.Sequence hiding (filter) import System.FilePath.Posix import System.Directory getUsefulContents :: FilePath -&gt; IO [FilePath] getUsefulContents path = fmap (filter (`notElem` [".", ".."])) $ getDirectoryContents path traverseTree :: (Proxy p) =&gt; FilePath -&gt; () -&gt; Producer (MaybeP (StateP (Seq FilePath) p)) FilePath IO r traverseTree path () = do liftP $ S.modify (|&gt; path) forever $ do x &lt;- liftP $ S.gets viewl case x of EmptyL -&gt; mzero file :&lt; s -&gt; do liftP $ S.put s respond file p &lt;- lift $ doesDirectoryExist file when p $ do names &lt;- lift $ getUsefulContents file let namesfull = map (file &lt;/&gt;) names liftP $ forM_ namesfull $ \name -&gt; S.modify (|&gt; name) </code></pre> <p>This defines a breadth-first lazy producer of files. If you hook it up to a printing stage, it will print out the files as it traverses the tree:</p> <pre><code>main = runProxy $ evalStateK empty $ runMaybeK $ traverseTree "/tmp" &gt;-&gt; putStrLnD </code></pre> <p>Laziness means that if you only demand 3 files, it will only traverse the tree as much as necessary to generate three files, then it will stop:</p> <pre><code> main = runProxy $ evalStateK empty $ runMaybeK $ traverseTree "/tmp" &gt;-&gt; takeB_ 3 &gt;-&gt; putStrLnD </code></pre> <p>If you want to learn more about the <a href="http://hackage.haskell.org/package/pipes" rel="nofollow"><code>pipes</code> library</a>, then I recommend you read <a href="http://hackage.haskell.org/packages/archive/pipes/3.1.0/doc/html/Control-Proxy-Tutorial.html" rel="nofollow">the tutorial</a>.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload