-
-
Save aisamanra/db05470d5a05088182db2cd85bc8d269 to your computer and use it in GitHub Desktop.
Some Resource Management Experiments
This file contains 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
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