I was thinking about self-referential lists in Haskell - for example you might
have the following script, fibonacci.hs
:
#!/usr/bin/env runghc
fibs :: [Integer]
fibs = 1:1:(zipWith (+) fibs $ tail fibs)
main :: IO ()
main = do
mapM_ print $ take 50 fibs
Because the filename extensions are so similar (just an xp
away), I reasoned
that something similar must be possible in a shell script, attaching a process'
stdout to its own stdin. All I could come up with is fibonacci.sh
:
#!/usr/bin/env sh
{ echo 1; echo 1; } > fibonaccis
tail -f fibonaccis |
python3 -c 'if True: # dummy to fix indentation
b = int(input())
for _ in range(48):
a, b = b, int(input())
print(a + b)' >> fibonaccis
cat fibonaccis
However I find it a bit unsatisfactory that I have to write everything to a file. Obviously this is a toy example, with far more optimal known algorithms, but what if I wanted simply to generate the 1000th Fibonacci number? It would then be unnecessary to retain the lines of stdout that the Python script wrote once it has consumed them.
So is there any better way of using a file to do this, or ideally a way to do this without a file, just using redirection? Or is this just unequivocally a terrible idea? Could this perhaps be done with a named pipe?
Whatever I have tried to search just comes up with ways to attach a process' stdout to the stdin of another process, which I am already vaguely familiar with. Bi-directional pipes doesn't seem to be exactly what I want either.
I am aware of the fact that some care will need to be taken to make sure the process is not buffering its I/O too liberally.