In Functional Programming, what is a functor?

后端 未结 17 686
孤独总比滥情好
孤独总比滥情好 2020-11-28 17:23

I\'ve come across the term \'Functor\' a few times while reading various articles on functional programming, but the authors typically assume the reader already understands

17条回答
  •  借酒劲吻你
    2020-11-28 17:38

    "Functor is mapping of objects and morphisms that preserves composition and identity of a category."

    Lets define what is a category ?

    It's a bunch of objects!

    Draw a few dots (for now 2 dots, one is 'a' another is 'b') inside a circle and name that circle A(Category) for now.

    What does the category holds ?

    Composition between objects and Identity function for every object.

    So, we have to map the objects and preserve the composition after applying our Functor.

    Lets imagine 'A' is our category which has objects ['a', 'b'] and there exists a morphism a -> b

    Now, we have to define a functor which can map these objects and morphisms into another category 'B'.

    Lets say the functor is called 'Maybe'

    data Maybe a = Nothing | Just a
    

    So, The category 'B' looks like this.

    Please draw another circle but this time with 'Maybe a' and 'Maybe b' instead of 'a' and 'b'.

    Everything seems good and all the objects are mapped

    'a' became 'Maybe a' and 'b' became 'Maybe b'.

    But the problem is we have to map the morphism from 'a' to 'b' as well.

    That means morphism a -> b in 'A' should map to morphism 'Maybe a' -> 'Maybe b'

    morphism from a -> b is called f, then morphism from 'Maybe a' -> 'Maybe b' is called 'fmap f'

    Now lets see what function 'f' was doing in 'A' and see if we can replicate it in 'B'

    function definition of 'f' in 'A':

    f :: a -> b
    

    f takes a and returns b

    function definition of 'f' in 'B' :

    f :: Maybe a -> Maybe b
    

    f takes Maybe a and return Maybe b

    lets see how to use fmap to map the function 'f' from 'A' to function 'fmap f' in 'B'

    definition of fmap

    fmap :: (a -> b) -> (Maybe a -> Maybe b)
    fmap f Nothing = Nothing
    fmap f (Just x) = Just(f x)
    

    So, what are we doing here ?

    We are applying the function 'f' to 'x' which is of type 'a'. Special pattern matching of 'Nothing' comes from the definition of Functor Maybe.

    So, we mapped our objects [a, b] and morphisms [ f ] from category 'A' to category 'B'.

    Thats Functor!

提交回复
热议问题