Anup Cowkur
Anup Cowkur

Reputation: 20563

Making Data.Map a functor in Haskell

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?

Upvotes: 13

Views: 2868

Answers (2)

DeadDork
DeadDork

Reputation: 71

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                 

Upvotes: 7

Tom Savage
Tom Savage

Reputation: 3182

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.

Upvotes: 16

Related Questions