Skip to content

Instantly share code, notes, and snippets.

@quchen
Created September 7, 2016 17:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save quchen/ebfb6eac7b775dce386e9babe7ec304f to your computer and use it in GitHub Desktop.
Save quchen/ebfb6eac7b775dce386e9babe7ec304f to your computer and use it in GitHub Desktop.
{-# 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