Skip to content

Instantly share code, notes, and snippets.

@jeremysinger
Created October 27, 2022 10:13
Show Gist options
  • Save jeremysinger/85b3bf0626c4c7e20b47dca595fc7a2f to your computer and use it in GitHub Desktop.
Save jeremysinger/85b3bf0626c4c7e20b47dca595fc7a2f to your computer and use it in GitHub Desktop.
{- Example code for Functional Programming
to demonstrate ad-hoc polymorphism with typeclasses
(c) Jeremy Singer 2022
-}
data Mammal = Human | Dog | Cat | Pig deriving (Show,Eq)
data Reptile = Crocodile deriving (Show,Eq)
class Noisy a where
mkNoise :: a -> String
instance Noisy Mammal where
mkNoise Dog = "woof"
mkNoise Cat = "meow"
mkNoise Pig = "oink"
mkNoise _ = "ow"
instance Noisy Reptile where
mkNoise Crocodile = "snap!"
verse :: (Show a, Noisy a) => a -> String
verse animal = "Old MacDonald had a farm, EIEIO\n" ++
"And on that farm he had some " ++ (show animal) ++ "s EIEIO\n" ++
"With a " ++ noiseTwice ++ " here and a " ++ noiseTwice ++ " there\n" ++
"Here a " ++ noiseOnce ++ ", there a " ++ noiseOnce ++ "\n" ++
"Everywhere a " ++ noiseTwice ++ "\n" ++
"Old MacDonald had a farm, EIEIO\n\n"
where noiseOnce = (mkNoise animal)
noiseTwice = noiseOnce ++ "-" ++ noiseOnce
song :: (Show a, Noisy a) => [a] -> String
song animals = concatMap verse animals
main = do
putStrLn $ song [Pig,Dog,Cat]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment