Skip to content

Instantly share code, notes, and snippets.

@aisamanra
Created August 2, 2016 21:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save aisamanra/db05470d5a05088182db2cd85bc8d269 to your computer and use it in GitHub Desktop.
Save aisamanra/db05470d5a05088182db2cd85bc8d269 to your computer and use it in GitHub Desktop.
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