1
votes

Given the following newtype:

newtype Bar a = Bar { foo :: Int -> a }

I tried to define a Functor instance for it.

instance Functor (Bar) where
    fmap g (Bar f) = Bar $ fmap f 

I intended to map over Int -> a to get Int -> b - I think that's the correct resultant type.

However, I got the compile-time error:

Couldn't match type `f0 Int' with `Int' 
Expected type: Int -> f0 a   
Actual type: f0 Int -> f0 a In the second argument of `($)', namely `fmap f' 
In the expression: Bar $ fmap f

How can I implement this Functor instance?

1

1 Answers

7
votes

It should be

instance Functor Bar where
    fmap g (Bar f) = Bar $ fmap g f

I think you might have just missed the g. You see f0 Int -> f0 a because f :: Int -> a so fmap f :: Functor f0 => f0 Int -> f0 a. Since g :: a -> b, you want to fmap g over f so that fmap g f :: Int -> b.