Skip to content

Instantly share code, notes, and snippets.

@Decoherence
Last active August 29, 2015 14:13
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 Decoherence/def77da358f314c5121a to your computer and use it in GitHub Desktop.
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.
-- | 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