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

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

petitviolet
September 19, 2015

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

Haskellで始める関数型プログラミング
ざっくりとした紹介とモナド
https://ngineerxiv.doorkeeper.jp/events/29760

petitviolet

September 19, 2015
Tweet

More Decks by petitviolet

Other Decks in Programming

Transcript

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

    • Fringe81͍ͬͯ͏ΞυςΫͷձࣾ • Android/iOSͷ޿ࠂSDK։ൃ 
  2. ؔ਺͸ԿͰ͋Δ͔Λ఻͑Δ • ϑΟϘφον਺ྻ // Python def fib(n): if n <

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

    1 : 1 : zipWith (+) fib (tail fib) take 10 fib 1, 1, 2, 3, 5, 8, 13, … 1, 1, 2, 3, 5, 8, 13, … 1, 1, 2, 3, 5, 8, 13,21… 
  4. ϥϜμࣜ Prelude> let add = \x y -> x +

    y Prelude> foldr add 0 [1..10] 55 
  5. ੩తܕ෇͚ && ܕਪ࿦ 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 
  6. • ܕͷ࣋ͭੑ࣭Λද͢ΠϯλʔϑΣʔεͬΆ͍ • Numʹଐ͢ܕ͸”਺”ͱͯ͠ͷੑ࣭Λ࣋ͭ ܕΫϥε Prelude> :t 10 10 ::

    Num a => a Prelude> :t 10 :: Int 10 :: Int :: Int Prelude> :t 10 :: Double 10 :: Double :: Double 
  7. Ϟφυͷલʹཧղ͍ͨ͠΍ͭ • ϑΝϯΫλʔ • ΞϓϦΧςΟϒϑΝϯΫλʔ 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 
  8. • จ຺Λ࣋ͭܭࢉΛ࣮ݱ͢Δ࢓૊Έ • 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])) [] 
  9. 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 SFUVSOB return 10 :: Maybe Int = Just 10  C monad B 
  10.