Skip to content

Instantly share code, notes, and snippets.

@rabingaire
Created April 6, 2022 11:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rabingaire/2c08c479707241261d87ff94e006e754 to your computer and use it in GitHub Desktop.
Save rabingaire/2c08c479707241261d87ff94e006e754 to your computer and use it in GitHub Desktop.
Haskell Typeclasses Example
data Coord = Coord Integer Integer
-- instance Eq Coord where
-- (==) (Coord x1 y1) (Coord x2 y2) = x1 == x2 && y1 == y2
instance Show Coord where
show (Coord x y) = "(" ++ show x ++ "," ++ show y ++ ")"
-- instance Eq Coord where
-- (==) c1 c2 = x1 == x2 && y1 == y2
-- where
-- (Coord x1 y1) = c1
-- (Coord x2 y2) = c2
instance Eq Coord where
c1 == c2 = x1 == x2 && y1 == y2
where
(Coord x1 y1) = c1
(Coord x2 y2) = c2
addCoord :: Coord -> Coord -> Coord
-- addCoord c1 c2 = Coord (x1 + x2) (y1 + y2)
-- where
-- (Coord x1 y1) = c1
-- (Coord x2 y2) = c2
addCoord (Coord x1 y1) (Coord x2 y2) = Coord (x1 + x2) (y1 + y2)
negateCoord :: Coord -> Coord
negateCoord (Coord x y) = Coord (- x) (- y)
multCoord :: Coord -> Coord -> Coord
multCoord (Coord x1 y1) (Coord x2 y2) = Coord (x1 * x2) (y1 * y2)
absCoord :: Coord -> Coord
absCoord (Coord x y) = Coord (abs x) (abs y)
sigNumCoord :: Coord -> Coord
sigNumCoord (Coord x y) = Coord v v where v = signum x * signum y
instance Num Coord where
(+) = addCoord
negate = negateCoord
(*) = multCoord
abs = absCoord
signum = sigNumCoord
fromInteger n = Coord n n
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment