Skip to content

Instantly share code, notes, and snippets.

@naoto-ogawa
Created January 15, 2017 07:27
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save naoto-ogawa/50edd6fdb92695b773acd6f089357077 to your computer and use it in GitHub Desktop.
Save naoto-ogawa/50edd6fdb92695b773acd6f089357077 to your computer and use it in GitHub Desktop.
Monad Logger Sample
-- {-# LANGUAGE OverloadedStrings #-}
import Data.Text
import Control.Monad.Trans
import Control.Monad.Trans.Maybe
import Control.Monad.Trans.State
import Control.Monad.Trans.Identity
import Control.Monad.Identity
import Control.Monad.Logger
--
-- MaybeT
--
-- >let w0 = do return 1:: MaybeT IO Int
-- >runMaybeT w0
-- Just 1
-- >let w0 = do return 2:: MaybeT IO Int
-- >runMaybeT w0
-- Just 2
-- >let w1 = do liftIO $ print "aaa"; return 2:: MaybeT IO Int
-- >runMaybeT w1
-- "aaa"
-- Just 2
--
-- Log + MaybeT
--
logMaybe00 :: LoggingT (MaybeT IO) Int
logMaybe00 = do
monadLoggerLog (Loc{loc_filename="monad_log_sample.hs", loc_module="foo", loc_package="bar", loc_start=(0,0), loc_end=(0,0)}) (pack "log source") LevelDebug (toLogStr $ pack "a")
liftIO $ putStrLn "logMaybe00"
return 2
-- >runMaybeT $ runStdoutLoggingT logMaybe00
-- [Debug#log source] a @(bar:foo monad_log_sample.hs:0:0)
-- logMaybe00
-- Just 2
logMaybe00' :: NoLoggingT (MaybeT IO) Int -- Change type from LoggingT to NoLoggingT, keeping the same implementaion.
logMaybe00' = do
monadLoggerLog (Loc{loc_filename="monad_log_sample.hs", loc_module="foo", loc_package="bar", loc_start=(0,0), loc_end=(0,0)}) (pack "log source") LevelDebug (toLogStr $ pack "a")
liftIO $ putStrLn "logMaybe00"
return 2
-- >runMaybeT $ runNoLoggingT logMaybe00'
-- logMaybe00
-- Just 2
-- >
--
logMaybe01 :: LoggingT (MaybeT IO) Int
logMaybe01 = do
msg <- liftIO $ getLine
mylog msg
liftIO $ putStrLn "aaa"
return 2
mylog :: MonadLogger m => String -> m ()
mylog msg = monadLoggerLog (Loc{loc_filename="", loc_module="", loc_package="", loc_start=(0,0), loc_end=(0,0)}) (pack "") LevelDebug (toLogStr $ pack msg)
-- >runMaybeT $ runStdoutLoggingT logMaybe01
-- zxzzxzxzx
-- [Debug] zxzzxzxzx @(: :0:0)
-- aaa
-- Just 2
-- >
--
-- StateT
--
state00 :: StateT [Int] IO Int
state00 = do
x:xs<-get
put xs
modify ((:) 9)
liftIO $ print x
return $ sum xs
-- >runStateT state00 [1,2,3]
-- 1
-- (5,[9,2,3])
-- >
--
--
-- Log + StateT
--
logState00 :: LoggingT (StateT [Int] IO) Int
logState00 = do
x:xs <- lift get
lift $ put xs
mylog $ "***" ++ (show xs) ++ "***"
x:xs <- lift get
lift $ put xs
mylog $ "***" ++ (show xs) ++ "***"
return 5
-- >runStateT (runStdoutLoggingT logState00) [1,2,3]
-- [Debug] ***[2,3]*** @(: :0:0)
-- [Debug] ***[3]*** @(: :0:0)
-- (5,[3])
-- >
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment