Search code examples
haskellfunctor

Define Writer Functor


Given any category C with products and an object c in C, we can define a functor _ × c : C -> C which maps an object a to a × c and a morphism f : a -> b to f × idc : a × c -> b × c.

I would like to implement such a functor in Haskell. I would like c to be String, so that the functor passes along logs.

I tried the following:

type Writer a = (a,String)

instance Functor Writer where    
  fmap :: (a -> b) -> Writer a -> Writer b.   
  fmap f (x,s) = (f x, s) 

However, I am getting an error which says "The type synonym ‘Writer’ should have 1 argument, but has been given none."


Solution

  • You work witha type synonym, and for a 2-tuple this is already defined.

    You can define a new type and make a Functor instance for this:

    data Writer a = Writer a String
    
    instance Functor Writer where    
      fmap f (Writer x s) = Writer (f x) s