Skip to content

Instantly share code, notes, and snippets.

@Unisay
Created March 13, 2018 20:43
Show Gist options
  • Save Unisay/3a80dc4039bdbcc8c2c1e2d3aa35b790 to your computer and use it in GitHub Desktop.
Save Unisay/3a80dc4039bdbcc8c2c1e2d3aa35b790 to your computer and use it in GitHub Desktop.
Nested brackets vs. ContT
module Control.Test where
import Data.Monoid
import Data.Functor
import Control.Exception
import Control.Monad.Trans.Cont
import Control.Monad.Trans.Class
import Text.Printf
open :: String -> IO String
open s = putStrLn ("Open: " <> s) $> s
close :: String -> IO ()
close s = putStrLn $ "Close: " <> s
br :: String -> (String -> IO a) -> IO a
br s = bracket (open s) close
withFoo :: (String -> IO a) -> IO a
withFoo = br "Foo"
withBar :: (String -> IO a) -> IO a
withBar = br "Bar"
withBaz :: (String -> IO a) -> IO a
withBaz = br "Baz"
allTogether :: String -> String -> String -> IO ()
allTogether = printf "All together %s %s %s\n"
{-
withFoo $ \foo ->
withBar $ \bar ->
withBaz $ \baz ->
allTogether foo bar baz
Open: Foo
Open: Bar
Open: Baz
All together Foo Bar Baz
Close: Baz
Close: Bar
Close: Foo
-}
withFoo' :: ContT r IO String
withFoo' = ContT withFoo
withBar' :: ContT r IO String
withBar' = ContT withBar
withBaz' :: ContT r IO String
withBaz' = ContT withBaz
{-
evalContT $ do
foo <- withFoo'
bar <- withBar'
baz <- withBaz'
lift $ allTogether foo bar baz
Open: Foo
Open: Bar
Open: Baz
All together Foo Bar Baz
Close: Baz
Close: Bar
Close: Foo
-}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment