2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Stateモナドを手で簡約してみたりしていた

Posted at

「モナド則だけみつめていたい」をつくった時の没ネタです。

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' 

とりあえず、モナド則

  1. join . fmap join = join . join
  2. join . fmap return = join . return = id
  3. return . f = fmap f . return
  4. 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))

参考文献

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?