Andrey
Andrey

Reputation: 15

How to write Functor instance

I have a following type data Summish a b = First a | Second b.

How to write Functor instance for it?

I tried

instance Functor (Summish a) where
  fmap f (Second a) = Second (f a)

Upvotes: 1

Views: 148

Answers (2)

Random Dev
Random Dev

Reputation: 52270

The easiest way is to let the compiler do (derive) it for you:

{-# LANGUAGE DeriveFunctor #-}

data Summish a b 
   = First a 
   | Second b
   deriving Functor

this only works if you have the derive functor extension enabled in GHC (for GHCi use :set -XDeriveFunctor).

So I guess you want/need to derive it manually.

As others stated you just need the case for First to make it exhaustive:

data Summish a b 
   = First a 
   | Second b

instance Functor (Summish a) where
   fmap f (First b) = First b
   fmap f (Second a) = Second (f a)

Upvotes: 5

sshine
sshine

Reputation: 16105

That is how you write a Functor instance.

The question is, is it a total, lawful instance?

If you add deriving Show to your data type, and you try to use this instance:

> fmap (+ 1) (Second 2)
Second 3

> fmap (+ 1) (First 2)
*** Exception: ...: Non-exhaustive patterns in function fmap

it seems that this Functor does not handle all possible values of Summish a b.

Upvotes: 1

Related Questions