Skip to content

Instantly share code, notes, and snippets.

@tiqwab
Last active July 25, 2016 14:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tiqwab/17c5bf444e90903c1779adb322d5c242 to your computer and use it in GitHub Desktop.
Save tiqwab/17c5bf444e90903c1779adb322d5c242 to your computer and use it in GitHub Desktop.
Readerモナドの整理
import Control.Monad.Reader
-- do構文でReaderモナド
-- runReader addStuffD 3 = 19
addStuffD :: Reader Int Int
addStuffD = do
x <- reader (*2)
y <- reader (+10)
return (x+y)
-- 明示的にbind
-- (>>=)の左辺はReader, 右辺の関数の引数は左辺で環境を使って計算された結果
addStuffB :: Reader Int Int
addStuffB = reader (*2) >>= \x -> reader (+10) >>= \y -> return (x+y)
-- ask = Reader id
-- local f m = Reader $ runReader m . f
-- `ask`は環境を返す。(`runReader askLocal 5` なら`5`)
-- `local f m`は環境をfで変換し、mに食わせる。
askLocal :: Reader Int Int
askLocal = do
e <- ask
l <- local (\x -> negate x) addStuffD
return l
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment