$30 off During Our Annual Pro Sale. View Details »

Functors

 Functors

Part 1 of the Functors, Monoids, and Monads presentation here: http://www.meetup.com/dynamic/events/222501291/

Kevin McCarthy

June 21, 2015
Tweet

More Decks by Kevin McCarthy

Other Decks in Programming

Transcript

  1. A monad is a monoid in the category of endofunctors,
    what's the problem?

    View Slide

  2. View Slide

  3. The magic of functional composition

    View Slide

  4. add2(1)
    add2(x) = x + 2
    3

    View Slide

  5. sub1(add2(1))
    sub1(x) = x - 1
    2

    View Slide

  6. crunch(5)
    crunch(x) = sub1(add2(x))
    6

    View Slide

  7. crunch(5)
    crunch = sub1 . add2
    6

    View Slide

  8. crunch([1,2,3])
    WTF?????

    View Slide

  9. FUNCTORS

    View Slide

  10. fcrunch([1,2,3])
    fcrunch = fmap crunch
    [2,3,4]

    View Slide

  11. class Functor f where
    fmap :: (a -> b) -> f a -> f b

    View Slide

  12. fmap transforms a “normal” function (g :: a -> b) into
    one which operates over containers/contexts (fmap
    g :: f a -> f b). This transformation is often referred to
    as a lift; fmap “lifts” a function from the “normal world”
    into the “f world”.

    View Slide

  13. *> :t add2
    add2 :: Num a => a -> a
    *> :t crunch
    crunch :: Num a => a -> a
    *> :t fcrunch
    fcrunch :: (Functor f, Num b) => f b -> f b

    View Slide

  14. instance Functor [] where
    fmap _ [] = []
    fmap g (x:xs) = g x : fmap g xs
    -- or we could just say fmap = map

    View Slide

  15. instance Functor Maybe where
    fmap _ Nothing = Nothing
    fmap g (Just a) = Just (g a)

    View Slide

  16. •[]
    •Tree
    •Map
    •Sequence
    •Maybe
    •IO

    View Slide

  17. MATH TIME

    View Slide

  18. –Wikipedia
    “In mathematics, a functor is a type of mapping
    between categories, which is applied in category
    theory. Functors can be thought of as
    homomorphisms between categories”

    View Slide

  19. Categories are bags of stuff that hold:
    • Objects
    • Morphisms
    Math

    View Slide

  20. Categories are bags of stuff that hold:
    • Types
    • Functions
    Code

    View Slide

  21. add2
    sub1
    Number
    f add2
    f sub1
    f Number
    Functor

    View Slide

  22. add2
    sub1
    10
    fmap add2
    fmap sub1
    [10]
    []
    LIFT

    View Slide

  23. FUNCTOR RULES
    Math

    View Slide

  24. FUNCTOR RULES
    •fmap id x = x
    •fmap(g.h) = (fmap g).(fmap h)
    Code

    View Slide

  25. BROKEN FUNCTOR
    instance Functor [] where
    fmap _ [] = []
    fmap g (x:xs) = g x : g x : fmap g xs

    View Slide