In Functional Programming, what is a functor?

后端 未结 17 702
孤独总比滥情好
孤独总比滥情好 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:54

    In a comment to the top-voted answer, user Wei Hu asks:

    I understand both ML-functors and Haskell-functors, but lack the insight to relate them together. What's the relationship between these two, in a category-theoretical sense?

    Note: I don't know ML, so please forgive and correct any related mistakes.

    Let's initially assume that we are all familiar with the definitions of 'category' and 'functor'.

    A compact answer would be that "Haskell-functors" are (endo-)functors F : Hask -> Hask while "ML-functors" are functors G : ML -> ML'.

    Here, Hask is the category formed by Haskell types and functions between them, and similarly ML and ML' are categories defined by ML structures.

    Note: There are some technical issues with making Hask a category, but there are ways around them.

    From a category theoretic perspective, this means that a Hask-functor is a map F of Haskell types:

    data F a = ...
    

    along with a map fmap of Haskell functions:

    instance Functor F where
        fmap f = ...
    

    ML is pretty much the same, though there is no canonical fmap abstraction I am aware of, so let's define one:

    signature FUNCTOR = sig
      type 'a f
      val fmap: 'a -> 'b -> 'a f -> 'b f
    end
    

    That is f maps ML-types and fmap maps ML-functions, so

    functor StructB (StructA : SigA) :> FUNCTOR =
    struct
      fmap g = ...
      ...
    end
    

    is a functor F: StructA -> StructB.

提交回复
热议问题