Skip to content

Instantly share code, notes, and snippets.

@gelisam
Created February 5, 2014 02:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gelisam/8816360 to your computer and use it in GitHub Desktop.
Save gelisam/8816360 to your computer and use it in GitHub Desktop.
A (contrived) use for NullaryTypeClasses
{-# 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