diff options
Diffstat (limited to 'ex2')
| -rw-r--r-- | ex2/Main.hs | 28 | ||||
| -rw-r--r-- | ex2/Shape.hs | 47 |
2 files changed, 65 insertions, 10 deletions
diff --git a/ex2/Main.hs b/ex2/Main.hs index 7e32c4a..74d0054 100644 --- a/ex2/Main.hs +++ b/ex2/Main.hs @@ -1,4 +1,28 @@ -import Shape +import Shape +main :: IO () main = do - putStrLn $ show $ square 5.0 + putStrLn "Convex Polygon:" + putStrLn + $ show + $ area + (polygon + [ (550, 450) + , (455, 519) + , (491, 631) + , (609, 631) + , (645, 519) + ] + ) + putStrLn "Concave Polygon:" + putStrLn + $ show + $ area + (polygon + [ (550, 580) + , (455, 519) + , (491, 631) + , (609, 631) + , (645, 519) + ] + ) diff --git a/ex2/Shape.hs b/ex2/Shape.hs index 0f7c0a9..97916c0 100644 --- a/ex2/Shape.hs +++ b/ex2/Shape.hs @@ -3,6 +3,7 @@ module Shape , area , square , circle + , polygon ) where @@ -16,30 +17,57 @@ type Radius = Float type Side = Float type Vertex = (Float, Float) +polygon :: [Vertex] -> Shape +polygon vs = Polygon vs + area :: Shape -> Float -area (Rectangle s1 s2) = s1 * s2 -area (RtTriangle s1 s2) = s1 * s2 / 2 +area (Rectangle s1 s2 ) = s1 * s2 +area (RtTriangle s1 s2 ) = s1 * s2 / 2 +area (Ellipse r1 r2 ) = pi * r1 * r2 +area (Polygon (v1 : vs)) = polyArea vs + where + polyArea :: [Vertex] -> Float + polyArea (v2 : v3 : vs') = triArea v1 v2 v3 + polyArea (v3 : vs') + polyArea _ = 0 -square :: Side -> Shape -square s = Rectangle s s +triArea :: Vertex -> Vertex -> Vertex -> Float +triArea v1 v2 v3 = + let a = distBetween v1 v2 + b = distBetween v2 v3 + c = distBetween v3 v1 + s = 0.5 * (a + b + c) + in sqrt (s * (s - a) * (s - b) * (s - c)) + +distBetween :: Vertex -> Vertex -> Float +distBetween (x1, y1) (x2, y2) = sqrt ((x1 - x2) ^ 2 + (y1 - y2) ^ 2) circle :: Radius -> Shape circle r = Ellipse r r +convex :: Shape -> Bool +convex (Rectangle a b ) = True +convex (RtTriangle a b ) = True +convex (Ellipse r1 r2) = True +convex (Polygon [_, _, _]) = True +convex (Polygon (vfirst : vsecond : vthird : vs)) = False + +crossProduct :: Vertex -> Vertex -> Vertex -> Float +crossProduct (x1, y1) (x2, y2) (x3, y3) = (x2 - x1) * (y3 - y2) - (y2 - y1) * (x3 - x2) + +square :: Side -> Shape +square s = Rectangle s s + rectangle :: Side -> Side -> Shape rectangle s1 s2 = Polygon [(x, y), (-x, y), (-x, -y), (x, -y)] where x = s1 / 2 y = s2 / 2 -rtTriangle :: Side -> Side -> Shape -rtTriangle s1 s2 = Polygon [(0, 0), (s1, 0), (0, s2)] - regularPolygon :: Int -> Side -> Shape regularPolygon n s = let angleinc = (pi * 2) / fromIntegral n - radius = (s * sin ((pi - angleinc) / 2)) / (sin angleinc) + radius = (s * sin ((pi - angleinc) / 2)) / sin angleinc regularVerts 0 _ = [] regularVerts n angle = (radius * cos angle, radius * sin angle) : regularVerts @@ -47,3 +75,6 @@ regularPolygon n s = (angle + angleinc) in Polygon (regularVerts n 0) + +rtTriangle :: Side -> Side -> Shape +rtTriangle s1 s2 = Polygon [(0, 0), (s1, 0), (0, s2)] |
