Skip to content

Instantly share code, notes, and snippets.

@jdoiwork
Created March 31, 2016 06:22
Show Gist options
  • Select an option

  • Save jdoiwork/0e66512e9f8227d1b6c4d5a812f1cb2a to your computer and use it in GitHub Desktop.

Select an option

Save jdoiwork/0e66512e9f8227d1b6c4d5a812f1cb2a to your computer and use it in GitHub Desktop.
Blaze.ByteString.Builder and Writer Monad
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Blaze.ByteString.Builder (toLazyByteString, Builder)
import Blaze.ByteString.Builder.ByteString (fromByteString)
import Data.String (IsString)
import Control.Monad.IO.Class (liftIO)
import Control.Monad.Writer (execWriterT, execWriter, WriterT, Writer, MonadWriter, tell)
import qualified Data.ByteString.Char8 as BS (getLine)
import qualified Data.ByteString.Lazy.Char8 as BL (putStrLn)
main :: IO ()
main = do
BL.putStrLn "Writer"
putBuilder $ execWriter logging
BL.putStrLn "Writer IO"
s <- execWriterT loggingIO
putBuilder s
putBuilder :: Builder -> IO ()
putBuilder = BL.putStrLn . toLazyByteString
type MyWriter = Writer Builder
type MyWriterIO = WriterT Builder IO
logging :: MyWriter ()
logging = do
tellLn "hoge 1"
tellLn "hoge 2"
tellLn "hoge 3"
return ()
loggingIO :: MyWriterIO ()
loggingIO = do
tellLn "hoge 1"
liftIO $ BL.putStrLn "hihi"
line <- liftIO $ fromByteString <$> BS.getLine
tellLn line
tellLn "hoge 2"
tellLn "hoge 3"
return ()
tellLn :: (IsString w, MonadWriter w m) => w -> m ()
tellLn w = do
tell w
tell "\n"
return ()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment