「モナド則だけみつめていたい」をつくった時の没ネタです。
Stateモナドを簡約すると何がおきてるかわかりやすいかなと思ったけど説明できるほどわかりやすくならなかった。
とりあえず、Stateモナドの定義
newtype State s a = State { runState :: (s -> (a,s)) }
instance Monad (State s) where
return a = State $ \s -> (a,s)
(State x) >>= f = State $ \s -> let (v,s') = x s in runState (f v) s'
とりあえず、モナド則
- join . fmap join = join . join
- join . fmap return = join . return = id
- return . f = fmap f . return
- join . fmap (fmap f) = fmap f . join
return 1
State (\s1 -> (1, s1))
return (return 1)
State (\s2 -> (return 1, s2))
State (\s2 -> (State (\s1 -> (1,s1)) ,s2))
join (return (return 1))
(return (return 1)) >>= id
State (\s2 -> (State (\s1 -> (1,s1)) ,s2)) >>= id
State $ (\s3 -> let (v,s3') = (\s2 -> (State (\s1 -> (1,s1)) ,s2)) s3 in runState (id v) s3')
State $ (\s3 -> let (v,s3') = (State (\s1 -> (1,s1)), s3) in runState v s3')
State (\s3 -> runState ((State (\s1 -> (1,s1))) s3
State (\s2 -> (\s1 -> (1,s1)) s2)
State (\s2 -> (1, s2))
参考文献