简体   繁体   中英

Is (fmap f) the same as (f .) if f is a function of type a->b?

I am trying to implement a Functor instance of

data ComplicatedA a b
    = Con1 a b
    | Con2 [Maybe (a -> b)]

For Con2, my thought process was the fmap needs to be something like

fmap f (Con2 xs) = Con2 (map f' xs)

then I need to have a list map function f' like

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

Since Maybe is a Functor, I can write f' like

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

In order to get ((a->x) -> (a->y)) , I thought I could just do fmap (x->y) which is the same as (fmap f)

So my sulotion was

instance Functor (ComplicatedA a) where
    fmap f (Con1 x y) = Con1 x (f y)
    fmap f (Con2 xs) = Con2 (map (fmap (fmap f)) xs)

However the real solution uses (f .) instead of (fmap f) to get ((a->x) -> (a->y)) from x -> y and it looks like this

instance Functor (ComplicatedA a) where
    fmap f (Con1 a b) = Con1 a (f b)
    fmap f (Con2 l) = Con2 (map (fmap (f .)) l)

I was just wondering what the problem was with my thought process and solution. Is (fmap f) the same as (f .) if f is a function of type a->b?

Thank you in advance.

The solutions are indeed equivalent. fmap for the function/reader functor is (.) :

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

( (->) r is the function type constructor being used with prefix syntax -- (->) ra is the same as r -> a .)

The intuition is that, as you have noted, (.) :: (x -> y) -> (a -> x) -> (a -> y) uses a x -> y function to modify the results of an a -> x function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM