This is a question about how to do something in Haskell, that is easy to do in Python3.
I have a Python3 program that uses generators, as follows:
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}")
If I give it an input file a.txt containing the following:
First line of a
b.txt
Third line of a
and another input file b.txt containing the following:
First line of b
Second line of b
then the output, as I would expect, is:
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
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.
In my attempts to write it in Haskell, I am getting in a dreadful mess with types like:
IO [IO String]
and I suspect that I'm going about it the wrong way.
Any suggestions?