Given the following algebraic type:
ghci> data Foo a = Foo a
Then I instantiate one of them.
ghci> let f = Foo "foo"
Lastly, I'd like to call fmap
to apply a function as, (a -> b) -> Foo a -> Foo b
.
ghci> fmap (++ "bar") f
<interactive>:78:1:
No instance for (Functor Foo) arising from a use of ‘fmap’
In the expression: fmap (++ "bar") f
In an equation for ‘it’: it = fmap (++ "bar") f
But, since I didn't implement a Functor
instance of Foo
, I can't use fmap
.
Is there a way to get Functor
instances for free? I have zero knowledge of Haskell's compiler, but perhaps it's clever enough to know that fmap
on Foo a
is simply apply (a -> b)
to Foo
's a
?
Functor T
for any givenT
, andDeriveFunctor
will produce that instance. Writing the instances by hand is an excellent way to understand them, though. I've learned a lot by studying the hand-written instances inbase
,free
,folds
, and many other libraries. – Christian Conkle