Search code examples
haskellmonadsfunctorapplicativealgebraic-data-types

How to create the instance for my own type?


I'm new to Haskell, learning Functor, Applicative, and Monad.

I checked the Functor instance for Either type from hackage is:

 data  Either a b  =  Left a | Right b

 instance Functor (Either a) where
    fmap _ (Left x) = Left x
    fmap f (Right y) = Right (f y)

and I am asked to do the Functor, Applicative, Monad instance for extended Either called MyEither:

data MyEither a b = MyLeft a | MyRight b | Nothing
    deriving (Eq, Show)

My question is:

1 How to extend Nothing in my instance?

2 Does deriving have to be written in the instance?

Can anyone get me some tips?


Solution

  • When you implement the instance you don't need to write deriving. deriving is for when you let the compiler derive an instance for you when you are defining a new type.

    For Nothing, pattern match on it and return Nothing for the implementation of all of FAM. There isn't much you can do with it.

    Here is a similar example that may help you.

    data Nope a = NopeDataJpg deriving (Eq, Show)
    
    instance Functor Nope where
      fmap _ _ = NopeDataJpg
      
    instance Applicative Nope where
      pure x = NopeDataJpg
      _ <*> _ = NopeDataJpg
    
    instance Monad Nope where
      return = pure
      _ >>= _ = NopeDataJpg
    

    Also, here are the Functor, Applicative, and Monad implementations of Maybe in GHC. How they handle Nothing is pretty similar to what you need to do for your data type.