13

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?

2 Answers 2

16

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Stupid me. That was it. Thanks!
myfmap f = M.fromList . map (second f) . M.toList hlint can help too
@TheInternet yup. Simpler than my current version. Thanks.
@AnupCowkur, this is a little more verbose, but more readable IMO. lpaste.net/98091
7

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                 

1 Comment

I honestly believe that Tom Savage's answer is more pedagogical, but I'm pretty sure that Miran was expecting something more along the lines of what I wrote (based on his code for a list as an instance of the Functor class).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.