confused about function as instance of Functor in haskell

前端 未结 5 1234
青春惊慌失措
青春惊慌失措 2020-12-14 16:58

the type of fmap in Functor is:

fmap :: Functor f => (a -> b) -> f a -> f b

it looks like ,first apply function (a -> b) to the

5条回答
  •  再見小時候
    2020-12-14 17:56

    The fmap instance for (->) r (i.e. functions) is literally just composition. From the source itself:

    instance Functor ((->) r) where
        fmap = (.)
    

    So, in your example, we can just replace fmap with (.), and do some transformations

    fmap (*3) (+100) 1 => 
    (.) (*3) (+100) 1  =>
    (*3) . (+100) $ 1  => -- put (.) infix
    (*3) (1 + 100)     => -- apply (+100)
    (1 + 100) * 3         -- apply (*3)
    

    That is, fmap for functions composes them right to left (exactly the same as (.), which is sensible because it is (.)).

    To look at it another way (for (double) confirmation!), we can use the type signature:

    -- general fmap
    fmap :: Functor f => (a -> b) -> f a -> f b
    
    -- specialised to the function functor (I've removed the last pair of brackets)
    fmap :: (a -> b) -> (r -> a) -> r -> b 
    

    So first the value of type r (the third argument) needs to be transformed into a value of type a (by the r -> a function), so that the a -> b function can transform it into a value of type b (the result).

提交回复
热议问题