Skip to content

Instantly share code, notes, and snippets.

@mmakowski
Created August 16, 2012 17:57
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 mmakowski/3372120 to your computer and use it in GitHub Desktop.
Save mmakowski/3372120 to your computer and use it in GitHub Desktop.
module Logger where
import System.IO
type Logger = String -> IO ()
data Logging a = Logging { unLogging :: Logger -> IO a }
logLine :: String -> Logging ()
logLine s = Logging $ \l -> l s
runLogging :: Logging a -> IO ()
runLogging (Logging logging) = do
log <- openFile "log.txt" WriteMode
logging $ hPutStrLn log
hClose log
(>>>=) :: Logging a -> (a -> Logging b) -> Logging b
(Logging l1) >>>= f = Logging $ \l -> l1 l >>= \x -> unLogging (f x) l
wrap :: a -> Logging a
wrap x = Logging $ \_ -> return x
instance Monad Logging where
return = wrap
(>>=) = (>>>=)
-- even better, we can just use standard monad functions, or even do syntax:
main :: IO ()
main = runLogging doSomething
doSomething :: Logging ()
doSomething = do
logLine "Hello Again"
x <- calcSomething "1234"
logLine (show x)
calcSomething :: String -> Logging Int
calcSomething s = do
logLine "calculating length"
return $ length s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment