Typeclasses, overloading and instance declaration

Having this:

data Rectangle = Rectangle Height Width
data Circle = Circle Radius

class Shape a where
    area :: a -> Float
    perimeter :: a -> Float

instance Shape Rectangle where
    area (Rectangle h w) = h * w
    perimeter (Rectangle h w) = 2*h+w*2

instance Shape Circle where
    area (Circle r) = pi * r**2
    perimeter (Circle r) = 2*pi*r

volumenPrism base height = (area base) * height

surfacePrism shape h = (area shape) * 2 + perimeter shape * h

Why can't I write this? ais a type, so why doesn't it work?

instance (Shape a) => Eq a where
      x==y = area x == area y

Obviously, he does the following:

instance Eq Circle where
     x==y = area x == area y

first for Circle and then for Rectangle works..but it seems like this is not the right way.

What I do not understand about all this?

T

+4
source share
1 answer

, . , instance Shape a => Eq a, , Eq, , , Shape.

,

{-# LANGUAGE FlexibleInstances, UndecidableInstances #-}

.

, OverlappingInstances . LANGUAGE, Eq, .

, , . ,

x `areaEq` y = area x == area y

instance Eq Circle where
    (==) = areaEq

.

+7

All Articles