Handle在Haskell中是半封闭的错误? [英] Handle is semi-closed error in Haskell?

查看:188
本文介绍了Handle在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆