I'm studying the basics of Haskell from Learn You a Haskell for Great Good!
There is an exercise in the book where you need to make Data.Map into a Functor.
I'm trying to make my own functor typeclass and make Data.Map into an instance of it.
So here's what I tried:
import Data.Map as DataMap
import Data.List as DataList
class MyFunctor f where
myfmap :: (a -> b) -> f a -> f b
instance MyFunctor (Ord k) => (DataMap.Map k) where
myfmap f x = DataMap.fromList $ DataList.map (\(p,q) ->(p,f q)) $ DataMap.toList x
When I try to compile this, GHCI gives me this error:
`myfmap' is not a (visible) method of class `Map'
I tried looking around other SO answers, blogs, mailing list threads etc without much luck.
The only thing I found was the description of the error message in the Haskell Wiki which says that GHCI throws this error when one tries to instantiate a class, but did not import the functions one tries to implement.
I have imported Data.Map and Data.List so I don't think that's the real cause.
What am I doing wrong?
yes map is a functor.
A Functor is an inbuilt class with a function definition like − class Functor f where fmap :: (a -> b) -> f a -> f b. By this definition, we can conclude that the Functor is a function which takes a function, say, fmap() and returns another function.
The syntax to define map in Haskell is as follows: [a]->[b] represents function being applied on each element in the list.
The Functor typeclass represents the mathematical functor: a mapping between categories in the context of category theory. In practice a functor represents a type that can be mapped over.
First thing I noticed is that your instance
syntax isn't quite right:
instance (Ord k) => MyFunctor (DataMap.Map k) where
...
Otherwise it seems fine.
Alternatively:
import qualified Data.Map as M
class Functor' f where
fmap' :: (a -> b) -> f a -> f b
instance (Ord k) => Functor' (M.Map k) where
fmap' = M.map
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With