Created
September 7, 2016 17:52
-
-
Save quchen/ebfb6eac7b775dce386e9babe7ec304f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{-# LANGUAGE LambdaCase #-} | |
-- | Teaching terrible coding practices with the help of purely functional | |
-- programming. Today: Node.hs! | |
module NodeHs where | |
import Control.Concurrent | |
import Control.Exception | |
import Control.Monad | |
import System.IO as SIO | |
withFile :: SIO.FilePath -> (SIO.Handle -> IO ()) -> IO () | |
withFile name | |
= nodify (openFile name ReadWriteMode) | |
hClose | |
(error . show) | |
nodify | |
:: IO resource -- ^ Acquire resource | |
-> (resource -> IO ()) -- ^ Release resource | |
-> (SomeException -> IO ()) -- ^ Exception handler | |
-> (resource -> IO ()) -- ^ Workhorse | |
-> IO () | |
nodify acquire release errorHandler action = bracket before after thing | |
where | |
before = acquire | |
after _ = pure () | |
thing resource = void (forkFinally (action resource) (\x -> do | |
release resource | |
case x of | |
Left e -> errorHandler e | |
Right _ -> pure () )) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment