6 ms·
Could you elaborate, please? Or point me to a discussion of the issues with said functions? Thanks!
by fp 17y ago
Could you elaborate, please? Or point me to a discussion of the issues with said functions? Thanks!
- loup-vaillant 17y agoIf I recall correctly, `getContent` (and therefore `interact`) uses `unsafeInterleaveIO`, the most unsafe function of the whole Haskell library, while not satisfying all the condition it should satisfy. More practically, `getContent` is evil because it locks the file it is reading for an unbounded amount of time: as long as it's content (the giant string representing the file), isn't either out of scope (and eventually garbage collected) or fully evaluated. That can be a problem if you intent to open loads of files (you could hit the OS limit) or if you want to modify the file after reading part of it. Lazy IO is therefore quite embarrassing. Several people are working at hopefully safer alternatives right now.
- shrughes 17y agoThey work by having input/output happen outside the IO monad. That breaks the abstraction -- which is impossible. You can't implement interact or getContents out of simpler functions, unless you use unsafeSomethingOrOtherIO.
- camccann 17y agoDo you have any references for that? I looked through some Haskell documentation and didn't see anything warning about those functions being unsafe (although there does seem to be an unsafeHGetContents in System.IO.Unsafe). Is there's something I'm missing that says "hey, this function uses unsafePerformIO behind the scenes" or whatnot? Being not very experienced with Haskell I'm a little worried about library functions being unsafe without me realizing it.
- jfoutz 17y agoIt's just getContents (and brother hGetContents). Using getContents is fine for a quick way to slurp in a file, but it's like doing a read without checking for -1. Since haskell is lazy, figuring out why an underlying read failed can be fairly confusing. If you think your program is doing IO and there's no IO type getting in the way, unsafePerformIO is lurking in the darkness.
- camccann 17y agoWell, I was confused because getContents seems to be of type "IO String": http://www.haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v%3AgetContents http://www.haskell.org/ghc/docs/latest/html/libraries/base/P... I can see why a lazy input stream could make things opaque even in a completely type-safe program, though.
- shrughes 17y agoThe behavior of hGetContents is documented at http://www.haskell.org/ghc/docs/latest/html/libraries/base/System-IO.html#v%3AhGetContents http://www.haskell.org/ghc/docs/latest/html/libraries/base/S... . If you write do h <- openFile "foo.txt" ReadMode x <- hGetContents h putStr x you'll get different behavior than if you write do h <- openFile "foo.txt" ReadMode x <- hGetContents h hClose h putStr x In the first example, you'll print out the contents of the file. In the latter, you'll print out nothing.