Created
February 5, 2014 02:15
-
-
Save gelisam/8816360 to your computer and use it in GitHub Desktop.
A (contrived) use for NullaryTypeClasses
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 NullaryTypeClasses, Rank2Types #-} | |
import Prelude hiding (log) | |
import Unsafe.Coerce | |
import System.IO.Unsafe | |
class NeedsInit | |
provideInit :: (NeedsInit => a) -> (() -> a) | |
provideInit = unsafeCoerce | |
log :: NeedsInit => String -> a -> a | |
log msg x = unsafePerformIO $ do | |
-- imagine this was an ffi call to some logging library | |
putStrLn msg | |
return x | |
initLog :: (NeedsInit => Int) -> Int | |
initLog x = let x' = provideInit x () in unsafePerformIO $ do | |
-- imagine this was initializing the logging library | |
putStrLn "init" | |
return x' | |
test :: NeedsInit => Int | |
test = log "left" 2 + log "right" 3 | |
-- No instance for NeedsInit | |
-- main = print test | |
-- typechecks! | |
main = print (initLog test) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment