Created
April 6, 2022 11:12
-
-
Save rabingaire/2c08c479707241261d87ff94e006e754 to your computer and use it in GitHub Desktop.
Haskell Typeclasses Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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