Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Defining a typeclass #10

Open
chris-martin opened this issue Sep 30, 2019 · 1 comment
Open

Defining a typeclass #10

chris-martin opened this issue Sep 30, 2019 · 1 comment
Labels
good for new contributors Pull requests welcome! new example This issue is about writing a new example program.

Comments

@chris-martin
Copy link
Member

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
@chris-martin chris-martin added good for new contributors Pull requests welcome! new example This issue is about writing a new example program. labels Sep 30, 2019
@zhujinxuan
Copy link

I think having an universal construction is a good reason for defining a type class.

I feel the Geometry is a bit too trivial for the example. I think a more real world example is semigroup (though haskell cannot gurantee associativity easily).

If you like, I can make a PR on it.

@BenBals BenBals mentioned this issue Oct 9, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
good for new contributors Pull requests welcome! new example This issue is about writing a new example program.
Projects
None yet
Development

No branches or pull requests

2 participants