Search code examples
haskellfunctor

Basic Functors in Haskell


I know that Functor typeclass is defined like so:

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

In my course it says that this is how a list is made an instance of functor:

instance Functor [] where  
    fmap = map  

Is [] a some kind of synonym for [a]?


Solution

  • Is [] a some kind of synonym for [a]

    Yes, precisely. There's no difference between the two types: the latter is only a pretty notation for the former.

    In Haskell, all types follow the syntax T arg1 arg2 ... where T is some type constructor, but some of them also have pretty notations hard-coded in the language for human convenience. Here's a few:

    a -> b   means (->) a b
    [a]      means [] a
    (a,b)    means (,) a b
    (a,b,c)  means (,,) a b c
    ... ditto for other tuple types
    

    Because of this, one can find a functor instance such as instance Functor ((->) a) whose fmap has type

    (x -> y) -> ((->) a x) -> ((->) a y)
    

    which can also be written

    (x -> y) -> (a -> x) -> (a -> y)
    

    Such fmap is just function composition, i.e., fmap = (.).