R – Having trouble writing the fmap

functorhaskell

I am trying to write an fmap for this type

data Triangle a  = Triangle {t0 :: Point a, t1 ::  Point a, t2 ::  Point a}

where Point is defined as

data Point a = Point {px :: a, py :: a, pz :: a}

And my instance def is

instance Functor Triangle where 
    fmap f (Triangle v0 v1 v2) = Triangle (f v0) (f v1) (f v2)

I am getting the following compliation error and I can't figure out why

 C:\Scripts\Haskell\Geometry.hs:88:1:
     Occurs check: cannot construct the infinite type: a = Point a
     When generalising the type(s) for `fmap'
     In the instance declaration for `Functor Triangle'

Any ideas?

Best Answer

instance Functor Point where
    fmap f (Point v0 v1 v2) = Point (f v0) (f v1) (f v2)

instance Functor Triangle where
    fmap f (Triangle v0 v1 v2) = Triangle (fmap f v0) (fmap f v1) (fmap f v2)

In the Triangle instance, f is a -> b. We have to convert it to Point a -> Point b first. Then we can make fmap f transform Triangle a to Triangle b. (Observe you're applying f to 9 objects, if I understood your intention correctly) [edit: was 27]

Related Topic