Discussion: Add safeWithFile function

Eric Mertens emertens at gmail.com
Sun Oct 12 16:05:45 UTC 2014


-1

This feels particularly ad-hoc and sets a strange precedent for "safe"
functions in base.

The overall better solution is to stop mixing lazy IO with withFile. In the
case that someone absolutely must have this, a local definition will be
best for other purple reading the code.
On Oct 11, 2014 2:11 PM, "David Feuer" <david.feuer at gmail.com> wrote:

> Some care is required to use withFile properly with lazy IO, and people
> sometimes get it wrong. In some cases, readFile is a suitable replacement.
> In other cases, however, it may be necessary to ensure the file gets closed
> in a timely manner, and it may not be necessary to read the whole file. The
> following seems to do the trick:
>
> safeWithFile :: (NFData a) => String -> IOMode -> (Handle -> IO a) -> IO a
> safeWithFile name mode f = withFile name mode $ f >=> (return $!!)
>
>
> Sample use:
>
> *SafeWithFile> safeWithFile "SafeWithFile.hs" ReadMode hGetContents >>=
> putStr
> module SafeWithFile (safeWithFile) where
> import Control.DeepSeq
> import System.IO
> import Control.Monad
>
> safeWithFile :: (NFData a) => String -> IOMode -> (Handle -> IO a) -> IO a
> safeWithFile name mode f = withFile name mode $ f >=> (return $!!)
>
> _______________________________________________
> Libraries mailing list
> Libraries at haskell.org
> http://www.haskell.org/mailman/listinfo/libraries
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/libraries/attachments/20141012/7f929d9a/attachment-0001.html>


More information about the Libraries mailing list