Stateモナドの解説 後編

1,307 views

Published on

Published in: Technology, Education, Travel
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
1,307
On SlideShare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
23
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

Stateモナドの解説 後編

  1. 1. State 2009 6 1 id:hiratara
  2. 2. • State • (>>=) State
  3. 3. (1) (>>=)
  4. 4. Int State Int Int f Int State Int Int
  5. 5. f Int State Int Int ∋ a f Int State Int Int ∋ 1 (a+1, 2) 2 (a+2, 3) ... s0 (a+s0, s0+1)
  6. 6. : f 10 2 12 1 (11, 2) f 10 = 2 (12, 3) ... s0 (10+s0, s0+1)
  7. 7. f 1 (2, 1) 2 (4, 2) ... s0 (s0 × 2, s0)
  8. 8. f 1 (2, 1) 2 (4, 2) ... s0 (s0 × 2, s0) (=<<) f 1 1 (3, 2) 2 2 (6, 3) ... f 2+1 = 3 s0 (s0 × 2 + s0, s0 + 1)
  9. 9. (>>=) (State x) >>= f = State $ s -> let (v,s') = x s in runState (f v) s' State(s0 ) (v(s0), s(s0)) ... (v, s') = (s0 × 2, s0) s = (s × 2, s) f v = f (s × 2) = (s × 2 + s0, s0 + 1) (f v) s' = (s × 2 + s0, s0 + 1) s = (s × 2 + s, s + 1) (s0 × 2, s0) >>= f = (s0 × 2 + s0, s0 + 1)
  10. 10. Int >>= State Int Int ∋ (s0 × 2, s0) (=<<) f f Int State Int Int ∋(s0 × 2 + s0, s0 + 1)
  11. 11. (1) • f • (>>=) f
  12. 12. (2) get put
  13. 13. put get • ( return (>>=) ) State • put get State
  14. 14. get • State • ( ) •
  15. 15. get • State • ( ) • → (s0, s0)
  16. 16. get get get = State $ s -> (s,s) → (s0, s0)
  17. 17. put s • State • () • s
  18. 18. put s • State • () • s → put s = ( (), s)
  19. 19. put s put put s = State $ _ -> ((),s) Int State Int Int put () State Int () → put s = ( (), s)
  20. 20. put s >>= put put s = State $ _ -> ((),s) Int State Int Int put (=<<) put () State Int () → put s = ( (), s)
  21. 21. (3)
  22. 22. State 0 1 1 1 2 2 2 3 3 ...
  23. 23. State 0 1 1 1 2 2 2 3 3 ... State Int Int 0 (1, 1) count = 1 (2, 2) ... s0 (s0 + 1, s0+1)
  24. 24. (s0 + 1, s0+1) = State Int Int 0 (1, 1) count = 1 (2, 2) ... s0 (s0 + 1, s0+1)
  25. 25. get put
  26. 26. Int get ∈ State Int Int put () State () Int () -> n+1 return Int State Int Int
  27. 27. put return >>= Int get ∈ State Int Int >>= put () State () Int return . ( ¥() -> n+1 ) >>= Int State Int Int
  28. 28. Int get = (s0, s0) ∈ State Int Int >>= put () ( (), s0 + 1) ∈ State () Int return . ( ¥() -> n+1 ) >>= Int ( s0 + 1, s0 + 1) ∈ State Int Int
  29. 29. • >>= • put get • do put get State
  30. 30. • runState evalState (v(s0), s(s0)) runState State Int Bool Int -> (Bool, Int) evalState Int Int -> Bool Int (Bool, Int) Bool

×