petitviolet
September 19, 2015
1.5k

# 初めての関数型プログラミング

ざっくりとした紹介とモナド
https://ngineerxiv.doorkeeper.jp/events/29760

## petitviolet

September 19, 2015

## Transcript

2. ### About Me • খࢵ ߂و(Hiroki Komurasaki) • @petitviolet • ৽ଔ1೥໨(15ଔ)

• Fringe81͍ͬͯ͏ΞυςΫͷձࣾ • Android/iOSͷ޿ࠂSDK։ൃ 

΋ͳͲ 
7. ### ७ਮؔ਺ܕʁ • ෭࡞༻͕ແ͍ • ࢀরಁաੑ • ಉ͡ೖྗʹରͯ͠͸ৗʹಉ͡ग़ྗ • ؔ਺͸ୈҰڃ •

jsͷΑ͏ʹؔ਺ΛΦϒδΣΫτͱͯ͠ѻ͑Δ 

13. ### ؔ਺͸ԿͰ͋Δ͔Λ఻͑Δ • ϑΟϘφον਺ྻ // Python def ﬁb(n): if n <

2: return n return ﬁb(n - 1) + ﬁb(n - 2) [ﬁb(i) for i in range(1, 11)] 
14. ### ؔ਺͸ԿͰ͋Δ͔Λ఻͑Δ • ϑΟϘφον਺ྻ // Haskell ﬁb :: [Int] ﬁb =

1 : 1 : zipWith (+) ﬁb (tail ﬁb) take 10 ﬁb 1, 1, 2, 3, 5, 8, 13, … 1, 1, 2, 3, 5, 8, 13, … 1, 1, 2, 3, 5, 8, 13,21… 
15. ### ஗ԆධՁ • ඞཁͳ෼͚ͩΛධՁ͢Δͷ͕஗ԆධՁ • ਺ྻࣗମΛఆٛग़དྷΔ • ﬁbؔ਺͸ແݶ௕ͷϑΟϘφον਺ྻΛฦ͢ // Haskell ﬁb

:: [Int] ﬁb = 1 : 1 : zipWith (+) ﬁb (tail ﬁb) ﬁb # ࢮ take 10 ﬁb 
16. ### ؔ਺߹੒ • Unixత • খ͞ͳؔ਺Λ૊Έ߹Θͤͯେ͖ͳ΋ͷΛ࡞Δ Prelude> length "hello" 5 Prelude>

show 100 "100" Prelude> (length . show) 100 3 
17. ### ϥϜμࣜ Prelude> let add = \x y -> x +

y Prelude> foldr add 0 [1..10] 55 

21. ### ੩తܕ෇͚ && ܕਪ࿦ Prelude> let a = 5 + 4

Prelude> :t a a :: Num a => a Prelude> let b :: Num a => a; b = (5 :: Num a => a) + (4 :: Num a => a) Prelude> :t b b :: Num a => a 
22. ### • ܕͷ࣋ͭੑ࣭Λද͢ΠϯλʔϑΣʔεͬΆ͍ • Numʹଐ͢ܕ͸”਺”ͱͯ͠ͷੑ࣭Λ࣋ͭ ܕΫϥε Prelude> :t 10 10 ::

Num a => a Prelude> :t 10 :: Int 10 :: Int :: Int Prelude> :t 10 :: Double 10 :: Double :: Double 

24. ### Ϟφυͷલʹཧղ͍ͨ͠΍ͭ • ϑΝϯΫλʔ • ΞϓϦΧςΟϒϑΝϯΫλʔ class Functor f where fmap

:: (a -> b) -> f a -> f b class (Functor f) => Applicative f where pure :: a -> f a (<*>) :: f (a -> b) -> f a -> f b 
25. ### • จ຺Λ࣋ͭܭࢉΛ࣮ݱ͢Δ࢓૊Έ • Maybe͸͋Δ͔΋͠Εͳ͍͠ɺͳ͍͔΋ • List͸ෳ਺ͷ஋͕͋Δ͔΋͠Εͳ͍ Ϟφυ Prelude> Just 10

>>= (\x -> Just(x + 4)) Just 14 Prelude> Nothing >>= (\x -> Just(x + 4)) Nothing 
26. ### • จ຺Λ࣋ͭܭࢉΛ࣮ݱ͢Δ࢓૊Έ • Maybe͸͋Δ͔΋͠Εͳ͍͠ɺͳ͍͔΋ • List͸ෳ਺ͷ஋͕͋Δ͔΋͠Εͳ͍ Ϟφυ Prelude> [1, 2]

>>= (\x -> [10, 20] >>= (\y -> [x, y])) [1,10,1,20,2,10,2,20] Prelude> [1, 2] >>= (\x -> [] >>= (\y -> [x, y])) [] 
27. ### class Monad m where return :: Monad m => a

-> m a (>>=) :: Monad m => m a -> (a -> m b) -> m b … B monad  C monad  Just 10 >>= (\x -> Just(show x)) = Just “10” B monad SFUVSOB return 10 :: Maybe Int = Just 10  C monad B 
28. ### • จ຺Λ࣋ͭ஋ಉ࢜ͷܭࢉΛ៉ྷʹ΍ΔͨΊͷ࢓૊Έ • Ϟφυ஋ͱɺϞφυ஋ΛฦΓ஋ͱ͢Δؔ਺Λ ͍͍ײ͡ʹ૊Έ߹ΘͤͯϞφυ஋ΛಘΔ • ܭࢉ݁ՌΛϞφυ஋ʹ͢Δ • Just 10

ͱ show Λ࢖ͬͯJust “10” • ࣦഊͯͨ͠ΒશମΛࣦഊͤ͞Δ • Nothing Λ show ͠Α͏ͱ͢Δͱ Nothing Ϟφυ 