I am new to Haskell, trying to understand Functor. I took following code from Data.Either module (Replaced data Either with Either1). I just updated by removing 'Either1 a' and replaced it with 'Either1' (instance Functor Either1 where).
data Either1 a b = Left1 a | Right1 b
instance Functor Either1 where
fmap f (Left1 x) = Left1 x
fmap f (Right1 y) = Right1 (f y)
When i try to load above snippet, I am getting following error.
Prelude> :load Sample.hs
[1 of 1] Compiling Main ( Sample.hs, interpreted )
Sample.hs:3:18:
Expecting one more argument to ‘Either1’
The first argument of ‘Functor’ should have kind ‘* -> *’,
but ‘Either1’ has kind ‘* -> * -> *’
In the instance declaration for ‘Functor Either1’
Failed, modules loaded: none.
My question is, Why should I put "Either1 a" while defining fmap function, why can't 'Either1" ?
As noted in the answer to your previous question, functors require a type of kind * -> *. Either1 has kind * -> * -> *; you need to partially apply Either1 to get a type of the proper kind.
> :k Either1
Either1 :: * -> * -> *
> :k Either1 Int
Either1 Int :: * -> *
When defining the Functor instance, it doesn't really matter to the functor what the first type is, so you can just specify an unconstrained type variable instead of a concrete type like Int.
When you implement Functor, you need a type that accepts a single type argument. Either1 accepts two type arguments, a and b, so your definition should look like this:
instance Functor (Either1 a) where
fmap f (Left1 x) = Left1 x
fmap f (Right1 y) = Right1 (f y)
(I also fixed a compilation error in the Left1 case; you were missing the f parameter)
The online book, Learn You a Haskell has a great introduction on Functors which talks in depth about the partial application of Either described here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With