Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 570
Anup Cowkur Avatar asked Jan 07 '14 11:01

Anup Cowkur


People also ask

Is map a functor?

yes map is a functor.

How do you define a functor Haskell?

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.

How do I map a function in Haskell?

The syntax to define map in Haskell is as follows: [a]->[b] represents function being applied on each element in the list.

Is functor a Typeclass?

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.


2 Answers

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.

like image 109
Tom Savage Avatar answered Oct 10 '22 03:10

Tom Savage


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                 
like image 39
DeadDork Avatar answered Oct 10 '22 03:10

DeadDork