public
Created

  • Download Gist
logger.hs
Haskell
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
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

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.