Reputation: 87
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
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