Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Category theory and Haskell

USAMI Kosuke
August 04, 2018

Category theory and Haskell

USAMI Kosuke

August 04, 2018
Tweet

More Decks by USAMI Kosuke

Other Decks in Science

Transcript

  1. ࣗݾ঺հ • Ӊࠤݟ ެีʢ͏͞Έ ͜͏͚͢ʣ • twitter: @usamik26 / connpass:

    usami-k • େֶ࣌୅͸਺ֶઐ߈ • Ͱ΋ݍ࿦͸΄ͱΜͲ΍ͬͯͳ͍ • ຊ৬͸ϓϩάϥϚʢϑΣϯϦϧגࣜձࣾʣ • Ͱ΋Haskell͸࢖ͬͯͳ͍
  2. ݍͷఆٛ • ର৅ , , , ... • ࣹ •

    ࣹͷ߹੒ ʢ͜͜Ͱ , ʣ • ݁߹཯ • ߃౳ࣹ ʢ೚ҙͷର৅ ʹ͍ͭͯଘࡏ͢Δʣ • ୯Ґݩ
  3. ର৅͸ Haskell ͷܕͱ͢Δ • جຊσʔλܕ : Int, Char, ... •

    Ϧετ : [Int], [Char], ... • Maybe ܕ : Maybe Int, Maybe Char, ... ͳͲͷ΋ͷ͕ର৅ • Maybe ܕʹ͍ͭͯิ଍ : Maybe Int ͷ஋͸ Just 0, Just 1, ... ·ͨ͸ Nothing
  4. ࣹ͸ Haskell ͷؔ਺ͱ͢Δ incr :: Int -> Int incr x

    = x + 1 • incr ͸ Int ܕͷ஋Λड͚औΓ Int ܕͷ஋Λฦؔ͢਺ • ͜ΕΛ Int ͔Β Int ΁ͷࣹͱΈͳ͢ • ͜ͷର৅ͱࣹʹΑͬͯݍ͕Ͱ͖Δ : Ҏޙ ͱॻ͘ • ͳ͓ɺ߃౳ࣹ͸߃౳ؔ਺ idɺ߹੒͸ؔ਺߹੒ (.)
  5. Ҿ਺Λෳ਺࣋ͭؔ਺͸ʁ add :: Int -> Int -> Int add x

    y = x + y • add ͸ೋͭͷ Int ܕͷ஋Λड͚औΓ Int ܕͷ஋Λฦؔ͢਺ • ɾɾɾͱ͍͏ղऍͷ··ͩͱ ͷࣹͰ͸ͳ͍
  6. ΧϦʔԽ add :: Int -> (Int -> Int) • add

    ͸ Int ܕͷ஋Λड͚औΓ Int -> Int ܕͷ஋Λฦ͢ add 3 :: Int -> Int (add 3) y = 3 + y -- `add 3` ͸ʮ3 Λ଍ؔ͢਺ʯͰ͋Δ • Int -> Int ͸ؔ਺ͷܕͰ͋Γɺ ͷର৅ • add ͸ର৅ Int ͔Β Int -> Int ΁ͷ ͷࣹ
  7. ༨ஊ • ଟҾ਺ؔ਺Λ1Ҿ਺ؔ਺ͱΈͳ͢ํ๏ͱͯ͠λϓϧ΋ߟ͑ΒΕΔ • (Int, Int) -> Int • ͔͠͠ɺHaskell

    ͷΧϦʔԽͷ΄͏͕ɺݍ࿦ʹద߹ͤ͞Δͱ ͍͏ҙຯͰ͸ΤϨΨϯτͩͱࢥΘΕΔ
  8. ؔखͷఆٛ • ݍ͔Βݍ΁ͷؔख • ͕ ͷର৅ ͸ ͷର৅ • ͕

    ͷࣹ ͸ ͷࣹ • ͷ߃౳ࣹ ʹ͍ͭͯ • ͷ߹੒ ʹ͍ͭͯ
  9. Haskell ʹ͓͚Δؔख class Functor f where fmap :: (a ->

    b) -> (f a -> f b) • Functor ͱ͍͏ܕΫϥε͕͋Δ • ͜Ε͕࣮ࡍʹݍ࿦ʹ͓͚Δؔखͷ֓೦ʹ͋ͨΔ΋ͷ • ΑΓ໌ࣔతʹݴ͏ͱɺFunctor ܕΫϥεͷΠϯελϯε͕ؔख
  10. ؔखͷྫ Maybe • Maybe ͸ Functor ܕΫϥεͷΠϯελϯε • ͜Ε͸ɺݍ ͔Βݍ

    ΁ͷؔखͰ͋Δ • Maybe ͸೚ҙͷܕ T ͔Β৽͍͠ܕ Maybe T Λ࡞Δ • Int ͔Β Maybe Int, Char ͔Β Maybe Char, ... • ͭ·Γɺ ͷର৅Λ ͷର৅ʹ͏ͭ͢
  11. ؔखͷྫ Maybe fmap :: (a -> b) -> (Maybe a

    -> Maybe b) fmap f :: Maybe a -> Maybe b fmap f (Just x) = Just (f x) fmap f Nothing = Nothing • f :: a -> b Λ fmap f :: Maybe a -> Maybe b ʹ • ͭ·Γɺ ͷࣹΛ ͷࣹʹ͏ͭ͢ • ͕ͨͬͯ͠ɺMaybe ͸ ͔Β ΁ͷؔख
  12. Functor ͰԿ͕خ͍͠ͷ͔ • Maybe Int ܕͷ஋Λͦͷ··ѻ͓͏ͱ͢Δͱ৔߹෼͚͕ඞཁ • ஋Λ࣋ͭ Just 1

    ͳͲͷ৔߹ • ஋Λ࣋ͨͳ͍ Nothing ͷ৔߹ • Functor ͷߟ͑Λ࢖͑͹ɺNothing ͷ͜ͱ͸๨Ε͍͍ͯ • Int ʹ͍͚ͭͯͩؔ਺ఆٛ͢Ε͹͍͍
  13. ྫ : ؔखʹͳΒͳ͍΋ͷ CMaybe a = CNothing | CJust Int

    a fmap f CNothing = CNothing fmap f (CJust counter x) = CJust (counter + 1) (f x) ҎԼͷΑ͏ʹ߃౳ࣹΛอͨͳ͍ɺ·ͨ߹੒΋อͨͳ͍ fmap id (CJust 0 "abc") -- CJust 1 "abc" id (CJust 0 "abc") -- CJust 0 "abc"
  14. ͞ΒͳΔ࿩୊ • ݍ࿦ʹ͓͚ΔϞφυ : ࣗݾؔखͰࣗવม׵Λ࣋ͭ΋ͷ • Haskell Ͱॏࢹ͞ΕΔͷ͸ϞφυʢMonadʣ • Monad

    ಉ࢜ΛνΣΠϯͤ͞Δ͜ͱ͕Ͱ͖Δ • ෭࡞༻Λ Monad ʹด͡ࠐΊΔ͜ͱ͕Ͱ͖Δ • ͦΕ͸·ͨͦͷ͏ͪɾɾɾ