longroad
longroad

Reputation: 87

Haskell methode of class is not visible for instance

I'm trying to define a class "Polygon" and subtypes "Triangle" and "Quad". Those should implement the area function of Polygon.

So I tried to make an instance of Polygon, but this doesn't works.

class Polygon a where

area :: a -> Float

data Triangle = MkTriangle {
                        tP1 :: Point,
                        tP2 :: Point,
                        tP3 :: Point}
                        deriving(Show)

data Quad = MkQuad{
                    qP1 :: Point,
                    qP2 :: Point,
                    qP3 :: Point,
                    qP4 :: Point}
                    deriving(Show)

instance Polygon Triangle where
    area triangle = 5.0

Note that area triangle = 5.0 is just debugging and not the real function. Trying to compile this, I am getting the following error:

    `area' is not a (visible) method of class `Polygon'
   |
57 |         area triangle = 5
   |         ^^^^
Failed, no modules loaded.

Can you give me a hint to fix that? Thank you!

Upvotes: 2

Views: 229

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477210

You need to indent the area method such that it is in the scope of the Polygon class, like:

class Polygon a where
    area :: a -> Float

By defining it with the same indentation level, you defined an empty typeclass, and created a function signature area without a binding.

Upvotes: 4

Related Questions