Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handle is semi-closed error in Haskell?

Tags:

io

haskell

handle

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?

like image 394
Ford O. Avatar asked Dec 25 '22 03:12

Ford O.


1 Answers

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
like image 99
R B Avatar answered Dec 29 '22 11:12

R B