title: How do I handle an infinite list of IO objects in Haskell?
body: <p>I'm writing a program that reads from a list of files.  The each file either contains a link to the next file or marks that it's the end of the chain.</p>
  
  <p>Being new to Haskell, it seemed like the idiomatic way to handle this is is a lazy list of possible files to this end, I have</p>
  
  <pre><code>getFirstFile :: String -&gt; DataFile
  getNextFile :: Maybe DataFile -&gt; Maybe DataFile
  
  loadFiles :: String -&gt; [Maybe DataFile]
  loadFiles = iterate getNextFile . Just . getFirstFile
  
  getFiles :: String -&gt; [DataFile]
  getFiles = map fromJust . takeWhile isJust . loadFiles
  </code></pre>
  
  <p>So far, so good.  The only problem is that, since getFirstFile and getNextFile both need to open files, I need their results to be in the IO monad.  This gives the modified form of</p>
  
  <pre><code>getFirstFile :: String -&gt; IO DataFile
  getNextFile :: Maybe DataFile -&gt; IO (Maybe DataFile)
  
  loadFiles :: String -&gt; [IO Maybe DataFile]
  loadFiles = iterate (getNextFile =&lt;&lt;) . Just . getFirstFile
  
  getFiles :: String -&gt; IO [DataFile]
  getFiles = liftM (map fromJust . takeWhile isJust) . sequence . loadFiles
  </code></pre>
  
  <p>The problem with this is that, since iterate returns an infinite list, sequence becomes an infinite loop.  I'm not sure how to proceed from here.  Is there a lazier form of sequence that won't hit all of the list elements?  Should I be rejiggering the map and takeWhile to be operating inside the IO monad for each list element?  Or do I need to drop the whole infinite list process and write a recursive function to terminate the list manually?</p>