Created
January 24, 2019 15:48
-
-
Save ch3pjw/41bc429d8f9503ab6c343aad11279ffc to your computer and use it in GitHub Desktop.
Preventing return of a resource from a bracket
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
{-# LANGUAGE | |
RankNTypes | |
#-} | |
module Main where | |
data MyResource a = MyResource {unMyResource :: String} | |
withMyResource :: String -> (forall a. MyResource a -> IO r) -> IO r | |
withMyResource s f = f (MyResource s) | |
main :: IO () | |
main = do | |
withMyResource "hello" | |
$ \res -> putStrLn $ unMyResource res | |
-- Does not compile: | |
-- sneakyRes <- withMyResource "world" | |
-- $ \res -> return res | |
-- putStrLn $ unMyResource sneakyRes |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The trick is the rank 2 type of
withMyResource
that lets it dictate the type of the passed function. You should get the following warning if you try to compile the commented section: