Search code examples
haskelliohandle

Handle is semi-closed error in Haskell?


I am getting this error in GHCI :

*** Exception: <stdin>: hGetLine: illegal operation (handle is semi-closed)

After running this code :

main = do
    interact $ unlines . fmap proccess . take x . lines
    readLn :: IO Int

And I am pretty sure the cause is take x. Is there any better way to read only x lines of input using interact or is interact just a solo player?


Solution

  • What you're trying to do isn't possible with interact. Behind the scenes interact claims the entirety of stdin for itself with hGetContents. This puts the handle into a “semi-closed” state, preventing you from attempting any further interaction with the handle besides closing it, as the entirety of its input has already been consumed (lazily).

    Try reading a finite number of lines with—

    import Control.Monad (replicateM)
    
    getLines :: Int -> IO [String]
    getLines n = replicateM n getLine