Project Inquiry

Measurable type-class

Challenge
{-# LANGUAGE NoImplicitPrelude #-}

module Main where

import           Prelude

main :: IO ()
main = putStrLn $ if test then "SUCCESS" else "FAILURE"

data Rectangle = Rectangle Double Double
data Circle = Circle Double -- e.g., radius

test :: Bool
test = and [ area (Rectangle 10.0 5.0) == 50.0
           , circumference (Rectangle 10.0 5.0) == 30.0
           , area (Circle 10.0) == 100.0 * pi
           , circumference (Circle 10.0) == 20.0 * pi
           ]

class Measurable s where
  area :: s -> Double
  circumference :: s -> Double

-- TODO: This program doesn't compile. Define the missing function(s) incl. type signatures!
Solution
{-# LANGUAGE NoImplicitPrelude #-}

module Main where

import           Prelude

main :: IO ()
main = putStrLn $ if test then "SUCCESS" else "FAILURE"

data Rectangle = Rectangle Double Double
data Circle = Circle Double -- e.g., radius

test :: Bool
test = and [ area (Rectangle 10.0 5.0) == 50.0
           , circumference (Rectangle 10.0 5.0) == 30.0
           , area (Circle 10.0) == 100.0 * pi
           , circumference (Circle 10.0) == 20.0 * pi
           ]

class Measurable s where
  area :: s -> Double
  circumference :: s -> Double

-- DONE
instance Measurable Rectangle where
  area (Rectangle a b) = a * b
  circumference (Rectangle a b) = 2 * a + 2 * b

instance Measurable Circle where
  area (Circle r) = r ^ 2 * pi
  circumference (Circle r) = 2 * r * pi