Last active
August 29, 2015 14:13
-
-
Save Decoherence/def77da358f314c5121a to your computer and use it in GitHub Desktop.
Haskell: Functional dependency example -- for any instance of the Pet type class, the type of animal uniquely determines the sound it can make.
This file contains hidden or 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
-- | Sandbox Haskell package | |
{-# LANGUAGE FlexibleInstances #-} | |
{-# LANGUAGE MultiParamTypeClasses #-} | |
{-# LANGUAGE FunctionalDependencies #-} | |
module Main where | |
class Pet animal sound | animal -> sound where | |
speak :: animal -> sound | |
data Sound = Bark | Meow deriving (Show) | |
type Name = String | |
newtype Dog = Dog Name | |
newtype Cat = Cat Name | |
instance Pet Dog Sound where | |
speak (Dog _) = Bark | |
instance Pet Cat Sound where | |
speak (Cat _) = Meow | |
oscar :: Dog | |
oscar = Dog "Oscar" | |
felix :: Cat | |
felix = Cat "Felix" | |
main :: IO () | |
main = do | |
putStrLn "Dog says: " | |
print $ speak oscar | |
putStrLn "Cat says: " | |
print $ speak felix |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment