jacosro
jacosro

Reputation: 539

Instances and class in Haskell

I have the following code in Haskell:

module Shape where
type Height = Float
type Width  = Float
type Radius = Float
data Rectangle  = Rectangle Height Width 
data Circle = Circle Radius

class (Eq a, Show a) => Shape a where
   area :: a -> Float
   perimeter :: a -> Float

instance Shape Rectangle where
    area (Rectangle h w) = h * w
    perimeter (Rectangle h w) = h*2 + w*2
    show (Rectangle h w) = "rectangle "  ++ (show h) ++ " " ++ (show w)
    (==) (Rectangle h w) (Rectangle c d) = (h == c) && (w == d)


instance Shape Circle where
   area (Circle r) = pi * r**2
   perimeter (Circle r) = 2 * pi * r
   show (Circle r) = "circle " ++ (show r)
   (==) (Circle r) (Circle x) = r == x

and I want to add the instances of Show and Eq in order to define the new cases (e.g Rectangle * * == Rectangle * *) but I get the following problem:

[1 of 1] Compiling Shape           ( Shape.hs, interpreted )
Shape.hs:24:17: `show' is not a (visible) method of class `Shape'
Shape.hs:25:17: `==' is not a (visible) method of class `Shape'
Shape.hs:31:12: `show' is not a (visible) method of class `Shape'
Shape.hs:32:12: `==' is not a (visible) method of class `Shape'
Failed, modules loaded: none.

What that it means? And how can I make it work?


EDIT: The code now: (line 13 to 31)

instance Eq Rectangle where
    (Rectangle h w) == (Rectangle c d) = (h == c) && (w == d)

instance Show Rectangle where
    show (Rectangle h w) = "rectangle "  ++ (show h) ++ " " ++ (show w)

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

instance Eq Circle where
    (Circle r) == (Circle x) = r == x

instance Show Circle where
    show (Circle r) = "circle " ++ (show r)

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

The error:

[1 of 1] Compiling Shape           ( Shape.hs, interpreted )
Shape.hs:19:5: parse error on input `instance'
Failed, modules loaded: none.

Upvotes: 2

Views: 415

Answers (1)

Louis Wasserman
Louis Wasserman

Reputation: 198511

Split out the instances for each type and each typeclass it's an instance of.

instance Eq Rectangle where
    (==) (Rectangle h w) (Rectangle c d) = (h == c) && (w == d)
instance Show Rectangle where
    show (Rectangle h w) = "rectangle "  ++ (show h) ++ " " ++ (show w)
instance Shape Rectangle where
    area (Rectangle h w) = h * w
    perimeter (Rectangle h w) = h*2 + w*2

It's just that the show and == definitions for each type aren't part of the Shape instance, they're part of typeclass instances for Show and Eq that happen to be dependencies of Shape.

Upvotes: 6

Related Questions