Created
February 22, 2018 02:18
-
-
Save mvolkmann/218bb32e29e88bc6f57075f6a536e300 to your computer and use it in GitHub Desktop.
learning about Haskell type classes
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
import qualified Data.Map as Map | |
-- A tuple of three Ints | |
type RGB = (Int, Int, Int) | |
-- Colors can be specified in three ways. | |
data Color = | |
ColorName String | | |
ColorHex String | | |
ColorRgb Int Int Int | |
-- This will be used convert from names to RGB values. | |
colorNameToRgbMap :: Map.Map String RGB | |
colorNameToRgbMap = Map.fromList [ | |
("red", (255, 0, 0)), | |
("green", (0, 255, 0)), | |
("blue", (0, 0, 255))] | |
-- A Wagon is one kind of thing that has a color. | |
data Wagon = Wagon { | |
length :: Int, | |
width :: Int, | |
color :: Color | |
} | |
-- This type class specifies the function signatures | |
-- for functions that should be implemented | |
-- for everything that has a color. | |
class HasColor a where | |
getColorName :: a -> String | |
getColorHex :: a -> String | |
getColorRgb :: a -> RGB | |
-- This implements the HasColor type class for the Wagon type. | |
instance HasColor Wagon where | |
-- How can these deal with all three ways of defining a color? | |
getColorName wagon = "some color name" | |
getColorHex wagon = "some hex value" | |
getColorRgb wagon = (1, 2, 3) | |
main :: IO () | |
main = do | |
let wagon = Wagon 36 20 (ColorName "red") | |
let name = getColorName wagon | |
putStrLn $ "name = " ++ name | |
let hex = getColorHex wagon | |
putStrLn $ "hex = " ++ hex | |
let rgb = getColorRgb wagon | |
putStrLn $ "rgb = " ++ show rgb |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment