Skip to content

Defining a typeclass #10

Description

@chris-martin

We wrote this a while back to show what defining your own typeclass looks like. I'm not sure whether I like it, or whether this is actually a good topic for a Phrasebook page (because "I want to define a typeclass" is not an end goal in itself). It would be cool to include an example like this if we could figure out how to motivate it better and change the title to something that is an understandably practical objective.

class Geometry a where
  area :: a -> Double
  perimeter :: a -> Double

data Rectangle =
  Rectangle
    { width :: Double
    , height :: Double
    }
  deriving Show

data Circle =
  Circle
    { radius :: Double
    }
  deriving Show

instance Geometry Rectangle where
  area r = width r * height r
  perimeter r = (2 * width r) + (2 * height r)

instance Geometry Circle where
  area c = pi * radius c * radius c
  perimeter c = 2 * pi * radius c

measure x =
  do
    putStrLn (show x)
    putStrLn ("area: " ++ show (area x))
    putStrLn ("perimeter: " ++ show (perimeter x))

main =
  do
    measure Rectangle{ width = 3, height = 4 }
    measure Circle{ radius = 5 }
$ runhaskell classes.hs
Rectangle {width = 3.0, height = 4.0}
area: 12.0
perimeter: 14.0
Circle {radius = 5.0}
area: 78.53981633974483
perimeter: 31.41592653589793

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    good for new contributorsPull requests welcome!new exampleThis issue is about writing a new example program.

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions