Created
August 16, 2012 17:57
-
-
Save mmakowski/3372120 to your computer and use it in GitHub Desktop.
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
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