summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorCarlos Sosa <gnusosa@gnusosa.net>2019-09-20 09:11:19 -0700
committerCarlos Sosa <gnusosa@gnusosa.net>2019-09-20 09:11:19 -0700
commite3c1b9511ad3d77e09bddfbadf10dae8725be65a (patch)
treeed591d2c4f0a2c2b0205e841f1e6af1d514dbeb1
First commit
-rw-r--r--README.org3
-rw-r--r--ex2/Main.hs4
-rw-r--r--ex2/Shape.hs49
3 files changed, 56 insertions, 0 deletions
diff --git a/README.org b/README.org
new file mode 100644
index 0000000..c255571
--- /dev/null
+++ b/README.org
@@ -0,0 +1,3 @@
+* The Haskell School of Expression solutions
+Here you will find solutions per chapter to all of the exercises found
+in the book The Haskell School of Expression.
diff --git a/ex2/Main.hs b/ex2/Main.hs
new file mode 100644
index 0000000..7e32c4a
--- /dev/null
+++ b/ex2/Main.hs
@@ -0,0 +1,4 @@
+import Shape
+
+main = do
+ putStrLn $ show $ square 5.0
diff --git a/ex2/Shape.hs b/ex2/Shape.hs
new file mode 100644
index 0000000..0f7c0a9
--- /dev/null
+++ b/ex2/Shape.hs
@@ -0,0 +1,49 @@
+module Shape
+ ( Shape
+ , area
+ , square
+ , circle
+ )
+where
+
+data Shape = Rectangle Side Side
+ | Ellipse Radius Radius
+ | RtTriangle Side Side
+ | Polygon [Vertex]
+ deriving Show
+
+type Radius = Float
+type Side = Float
+type Vertex = (Float, Float)
+
+area :: Shape -> Float
+area (Rectangle s1 s2) = s1 * s2
+area (RtTriangle s1 s2) = s1 * s2 / 2
+
+square :: Side -> Shape
+square s = Rectangle s s
+
+circle :: Radius -> Shape
+circle r = Ellipse r r
+
+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)
+ regularVerts 0 _ = []
+ regularVerts n angle =
+ (radius * cos angle, radius * sin angle) : regularVerts
+ (n - 1)
+ (angle + angleinc)
+ in
+ Polygon (regularVerts n 0)