Is (fmap f) the same as (f .) if f is a function o

2019-06-17 04:35发布

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.

1条回答
疯言疯语
2楼-- · 2019-06-17 05:06

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 -- (->) r a 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.

查看更多
登录 后发表回答