本文介绍了Haskell IO-hGetContents:非法操作(句柄已关闭)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图理解haskell IO,但stdin的这一功能最终使我感到困惑:当我尝试使用诸如getContents之类的功能时,例如:

I'm trying to comprehend haskell IO but this feature of stdin ultimately confuses me:When I try to use some function like getContents, for example in:

let main = do x<-getContents; putStrLn x

我收到以下错误:

hGetContents: illegal operation (handle is closed)

我应该如何对此做任何IO?是否有一些解决方法,还是我应该寻找另一个类比IO功能?

How I am supposed to do any IO with this? Is there some fix, or should I look up for another analogical IO function?

推荐答案

我建议您也研究一种替代方法. getContents和类似的操作存在一些固有的问题:

I'd suggest you to also investigate an alternative approach. There some inherent problems with getContents and similar operations:

  1. 您可以使用无效的句柄-已经关闭的句柄.这在大多数语言中都很常见,但我们可以做得更好.理想情况下,我们希望确保一旦关闭手柄,就无法再使用它了.
  2. getContents惰性IO ,这意味着(除其他问题外):
    • 当手柄关闭时,我们几乎无法控制 .
    • 虽然我们正在处理getContents返回的字符串,但使用懒惰的IO操作读取数据.这意味着在纯计算内部,我们可以得到IO的影响和错误.
  1. You can have an invalid handle - a handle that is already closed. This is common in most languages, but we can do better. Ideally, we'd like to be sure that once we close a handle, we can't use it further.
  2. getContents is a lazy IO, which means (among other problems) that:
    • We have little or no control of when (if) the handle is closed.
    • While we're processing the string returned by getContents, the data are read using lazy IO operations. This means that inside pure computations we can get IO effects and errors.

一个更安全的选择是使用另一个概念,称为迭代,管道或管道.想法是将组件描述为读取一些输入数据和/或写入输出,然后将它们组合在一起的事物.这使您可以编写非常健壮和优雅的代码.

A safer alternative is to use another concept, called iteratees, conduits or pipes. The idea is that you describe your components as things that read some input data and/or write output and then combine them together. This allows you to write very robust and elegant code.

这篇关于Haskell IO-hGetContents:非法操作(句柄已关闭)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-26 23:17