In Functional Programming, what is a functor?

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

    Given the other answers and what I'm going to post now, I'd say that it's a rather heavily overloaded word, but anyway...

    For a hint regarding the meaning of the word 'functor' in Haskell, ask GHCi:

    Prelude> :info Functor
    class Functor f where
      fmap :: forall a b. (a -> b) -> f a -> f b
      (GHC.Base.<$) :: forall a b. a -> f b -> f a
            -- Defined in GHC.Base
    instance Functor Maybe -- Defined in Data.Maybe
    instance Functor [] -- Defined in GHC.Base
    instance Functor IO -- Defined in GHC.Base
    

    So, basically, a functor in Haskell is something that can be mapped over. Another way to say it is that a functor is something which can be regarded as a container which can be asked to use a given function to transform the value it contains; thus, for lists, fmap coincides with map, for Maybe, fmap f (Just x) = Just (f x), fmap f Nothing = Nothing etc.

    The Functor typeclass subsection and the section on Functors, Applicative Functors and Monoids of Learn You a Haskell for Great Good give some examples of where this particular concept is useful. (A summary: lots of places! :-))

    Note that any monad can be treated as a functor, and in fact, as Craig Stuntz points out, the most often used functors tend to be monads... OTOH, it is convenient at times to make a type an instance of the Functor typeclass without going to the trouble of making it a Monad. (E.g. in the case of ZipList from Control.Applicative, mentioned on one of the aforementioned pages.)

提交回复
热议问题