Create a gist now

Instantly share code, notes, and snippets.

@aisamanra /resources.hs Secret
Created Aug 2, 2016

What would you like to do?
Some Resource Management Experiments
import Control.Exception.Base (bracket_)
import Debug.Trace (trace)
-- These are dummy types for the purposes of demonstration
data Request = Request
data Response = Response
data Done = Done
-- a basic, non-CPS App example
type App = Request -> IO Response
-- We're gonna bracket the return value here
myApp :: App
myApp request =
bracket_ (putStrLn "Normal: creating 'resource'")
(putStrLn "Normal: destroying 'resource'")
(case request of
Request -> return (trace "Normal: Forcing response" Response))
runApp :: App -> IO ()
runApp app = do
rs <- app (trace "Normal: Forcing request" Request)
case rs of
Response -> return ()
-- A CPS'ed App example
type App' = Request -> (Response -> IO Done) -> IO Done
myApp' :: App'
myApp' request f =
bracket_ (putStrLn "CPS: creating 'resource'")
(putStrLn "CPS: destroying 'resource'")
(case request of
Request -> f (trace "CPS: Forcing response" Response))
runApp' :: App' -> IO ()
runApp' app = do
rs <- app (trace "CPS: Forcing request" Request)
(\ r -> case r of
Response -> return Done)
case rs of
Done -> return ()
-- And running both:
main :: IO ()
main = do
putStrLn "Non-CPS'ed:"
runApp myApp
putStrLn ""
putStrLn "CPS'ed:"
runApp' myApp'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment