Haskell IO and closing files

后端 未结 6 2042
走了就别回头了
走了就别回头了 2021-01-30 21:21

When I open a file for reading in Haskell, I\'ve found that I can\'t use the contents of the file after closing it. For example, this program will print the contents of a file:<

6条回答
  •  误落风尘
    2021-01-30 21:38

    This is because hGetContents doesn't do anything yet: it's lazy I/O. Only when you use the result string the file is actually read (or the part of it that is needed). If you want to force it to be read, you can compute its length, and use the seq function to force the length to be evaluated. Lazy I/O can be cool, but it can also be confusing.

    For more information, see the part about lazy I/O in Real World Haskell, for example.

提交回复
热议问题