title: Mimicking Python generator, with IO, in Haskell
body: <p>This is a question about how to do something in Haskell, that is easy to do in Python3.</p>
  
  <p>I have a Python3 program that uses generators, as follows:</p>
  
  <pre><code>def gen(filename):
      for line in open(filename):
          line = line.rstrip()
          print(f"From {filename} about to yield the line {line}")
          yield line
          print(f"From {filename} recently yielded the line {line}")
          if "." in line:
              yield from gen(line)
  
  for line in gen("a.txt"):
      print(f"Main program has {line}")
  </code></pre>
  
  <p>If I give it an input file a.txt containing the following:</p>
  
  <pre><code>First line of a
  b.txt
  Third line of a
  </code></pre>
  
  <p>and another input file b.txt containing the following:</p>
  
  <pre><code>First line of b
  Second line of b
  </code></pre>
  
  <p>then the output, as I would expect, is:</p>
  
  <pre><code>From a.txt about to yield the line First line of a
  Main program has First line of a
  From a.txt recently yielded the line First line of a
  From a.txt about to yield the line b.txt
  Main program has b.txt
  From a.txt recently yielded the line b.txt
  From b.txt about to yield the line First line of b
  Main program has First line of b
  From b.txt recently yielded the line First line of b
  From b.txt about to yield the line Second line of b
  Main program has Second line of b
  From b.txt recently yielded the line Second line of b
  From a.txt about to yield the line Third line of a
  Main program has Third line of a
  From a.txt recently yielded the line Third line of a
  </code></pre>
  
  <p>I would very much like to be able to do the same thing in Haskell. I need to preserve the basic structure of the Python version, keeping gen() as a function (or semi-coroutine, if you want to call it that) that I can call from various different places.</p>
  
  <p>In my attempts to write it in Haskell, I am getting in a dreadful mess with types like:</p>
  
  <pre><code>IO [IO String]
  </code></pre>
  
  <p>and I suspect that I'm going about it the wrong way.</p>
  
  <p>Any suggestions?</p>