Handle在Haskell中是半封闭的错误? [英] Handle is semi-closed error in Haskell?
问题描述
***例外情况:< stdin>:hGetLine:非法操作(句柄为半
<$ <$ p
$ b运行此代码后:
c $ c> main = do
交互$ unlines。 fmap进程。采取x。
readLn :: IO Int
我确定原因是 take x
。有没有更好的方式来阅读只有 X使用交互行或是交互
只是一个独奏球员?
。在幕后 interact
为 hGetContents
。这使手柄变成了半封闭状态,因为它的整个输入已经被消耗(懒惰地),所以阻止你尝试进一步与句柄进行交互。尝试读取有限数字&$;
import Control.Monad(replicateM)
getLines :: Int - > IO [String]
getLines n = replicateM n getLine
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?
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
这篇关于Handle在Haskell中是半封闭的错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!