Deriving Functor - Haskell

Welcome to the Functional Programming Zulip Chat Archive. You can join the chat here.

Vincent L

Hi,
I see that it's possible to have deriving Functor after defining a type. While I can sortof guess what deriving Show do in general, I have trouble figuring how you can go from an ADT to a functor ? I mean wrapping/unwrapping constructor is not enough, the type of the parameter may change with function application

Torsten Schmits

In what way do you see a problem with function application?
GHC analyzes every field and generates an fmap that applies the f argument to each of these, then reassembles the type

Torsten Schmits

for a type

data A a = A (Maybe a) a

you'd get an fmap like

fmap f (A ma a) = A (fmap f ma) (f a)
Vincent L

if I have a type

data SomeType = A String | B Int | C Bool

then a functor would need to apply a function f to String, Int and Bool

Torsten Schmits

you can't derive a functor for a type without a parameter!

bradrn

SomeType isn’t a functor — functors must have at least one type argument.

Torsten Schmits

in that case it would be id

Torsten Schmits

well, it won't work, of course

bradrn

Actually, that reminds me of something I run into occasionally. Sometimes I have a type wrapping a value, where that value is a specific type rather than a type variable. Often in this case I need to write some sort of mapping function, but of course I can’t use Functor as the type of the wrapped value is invariant, so I just end up with lots of mapping functions. Does anyone know of a good class I can use for such functions, or some other way of solving the problem? (I do know about MonoFunctor, but that requires a mono-traversables dependency…)

Torsten Schmits

I'd say that's usually a case for lens

Daniel Díaz Carrete

You could make the type an actual Functor and declare a type synonym which "fixes" the parameter.