Skip to content

Instantly share code, notes, and snippets.

@BartMassey
Created October 8, 2018 19:58
Show Gist options
  • Select an option

  • Save BartMassey/111b1bedcdcf2bf39e25d98d007de9c1 to your computer and use it in GitHub Desktop.

Select an option

Save BartMassey/111b1bedcdcf2bf39e25d98d007de9c1 to your computer and use it in GitHub Desktop.
-- Modified from https://www.snoyman.com/blog/2018/10/raii-better-than-bracket-pattern
import Control.Exception (bracket)
import Text.Printf (printf)
data MyResource = MyResource { handle :: Int }
newMyResource :: IO MyResource
newMyResource = do
putStrLn "Creating a new MyResource"
pure MyResource { handle = 0 }
closeMyResource :: MyResource -> IO ()
closeMyResource resource = printf "Closing MyResource @ %d\n" (handle resource)
withMyResource :: (MyResource -> IO a) -> IO a
withMyResource = bracket newMyResource closeMyResource
useMyResource :: MyResource -> IO ()
useMyResource resource = printf "Using MyResource @ %d\n" (handle resource)
main :: IO ()
main = do
-- withMyResource useMyResource
myResource <- withMyResource pure
useMyResource myResource
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment