Skip to content

Instantly share code, notes, and snippets.

@tiqwab
Last active February 9, 2019 16:47
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tiqwab/cd7ebdedaae860716d2842262769b066 to your computer and use it in GitHub Desktop.
Save tiqwab/cd7ebdedaae860716d2842262769b066 to your computer and use it in GitHub Desktop.
Writerモナドの整理
import Control.Monad.Writer
-- do構文でWriter
logCalcD :: Writer [String] Int
logCalcD = do
tell ["Process start"]
x <- writer (1, ["Initial value: " ++ " 1"])
y <- writer (x * 2, ["Multiply by two"])
tell ["Process end"]
return y
-- 明示的にbind
-- (>>=)の左辺はWriter, 右辺の引数は前のWriterから得られた計算値(ここではInt型)
-- Writer w aの型wはモノイドでなければならない
logCalcB :: Writer [String] Int
logCalcB = tell ["Process Start"]
>>= \_ -> writer (1, ["Initial value: " ++ "1"])
>>= \x -> writer (x * 2, ["Multiply by two"])
>>= \y -> writer (y, ["Process end"])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment