Created
January 5, 2015 09:21
-
-
Save DaveCTurner/37258febb57ddaef99b0 to your computer and use it in GitHub Desktop.
The 'ClearBefore' monoid, adding the ability to clear a log generated by a Writer.
This file contains hidden or 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
-- ClearBefore.hs | |
module ClearBefore where | |
import Data.Monoid | |
data ClearBefore a = ClearBefore Bool a | |
instance Monoid a => Monoid (ClearBefore a) where | |
mempty = ClearBefore False mempty | |
mappend (ClearBefore f a) (ClearBefore False b) = ClearBefore f (mappend a b) | |
mappend _ x = x | |
runClearBefore :: ClearBefore a -> a | |
runClearBefore (ClearBefore _ a) = a | |
-- Main.hs | |
{-# LANGUAGE FlexibleContexts #-} | |
module Main (main) where | |
import ClearBefore | |
import Control.Applicative | |
import Control.Monad.Writer | |
tell_ :: MonadWriter (ClearBefore w) m => w -> m () | |
tell_ = tell . ClearBefore False | |
clear :: (Monoid w, MonadWriter (ClearBefore w) m) => m () | |
clear = tell $ ClearBefore True mempty | |
main :: IO () | |
main = do | |
log <- liftM runClearBefore $ execWriterT $ do | |
tell_ "a" | |
tell_ "b" | |
clear | |
liftIO $ putStrLn "within writer" | |
tell_ "c" | |
tell_ "d" | |
putStrLn $ "log: " <> log |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment