I'm new to programming, and I'm having trouble solving a task.
I have to use the translatePol
function to move each point of a polygon by one vector. In that case I have to implement it on a triangle.
I've tried different things but I'm just getting errors and that's why I'd like to ask for help.
type Point = (Float, Float)
type Vector = (Float, Float)
data PointD = MPoint Float Float
data VectorD = MVector Float Float
class Polygon p where
translatePol :: p -> VectorD -> Point
data Triangle = MTriangle {
tP1 :: Point,
tP2 :: Point,
tP3 :: Point}
deriving (Show)
Problem: I don't know how to write the following instance:
instance Polygon Triangle where
translatePol (MTriangle tP1 tP2 tP3) (MVector v1 v2)
= (tP1 v1,tP1 v2) (tP2 v1,tP2 v2) (tP3 v1,tP3 v2)
CodePudding user response:
First, points and vectors are two separate concepts, and should probably be distinct types, not just two different aliases for a 2-tuple.
data Point = Pt Float Float
data Vector = V Float Float
Second, your type class seems to capture the idea of translating collections of points using the same vector. The return type should then be the same as the first argument type, not hard-coded to Point
.
class Polygon p where
translatePol :: p -> VectorD -> p
Now you can start simple, and define a Polygon
instance for Point
. (Think of a point as a degenerate polygon.)
instance Polygon Point where
translatePol (Pt x y) (Mvector v1 v2) = Pt (x v1) (y v2)
This can be used to define the instance for Triangle
more simply.
instance Polygon Triangle where
translatePol (MTriangle p1 p2 p3) v = MTriangle (t p1) (t p2) (t p3)
where t p = translatePol p v