Skip to content

Instantly share code, notes, and snippets.

@avernet
Created February 18, 2012 01:57
Show Gist options
  • Save avernet/1856860 to your computer and use it in GitHub Desktop.
Save avernet/1856860 to your computer and use it in GitHub Desktop.
Polymorphism in Haskell
module EasternOrder where
import Serializable
import Person
instance IsSerializable Person where
serialize (Person f l) = l ++ " " ++ f
easternOrder :: Person -> Serializable
easternOrder = Serializable
module EuropeanOrder where
import Serializable
import Person
instance IsSerializable Person where
serialize (Person f l) = f ++ " " ++ l
europeanOrder :: Person -> Serializable
europeanOrder = Serializable
import Person
import Serializable
import EuropeanOrder
import EasternOrder
us = europeanOrder (Person "Barack" "Obama")
cn = easternOrder (Person "Jintao" "Hu")
main = (print . serializeAll) [us, cn]
import Person
import Serializable
import EuropeanOrder
main = (print . serialize) (Person "Barack" "Obama")
module Person where
data Person = Person String String
import Person
import Serializable
import EuropeanOrder
import EasternOrder
us = europeanOrder (Person "Barack" "Obama")
cn = easternOrder (Person "Jintao" "Hu")
main = (print . serializeAll) [us, cn]
module Serializable where
import Data.List
class IsSerializable a where
serialize:: a -> String
data Serializable where
Serializable :: IsSerializable a => a -> Serializable
serializeAll:: [Serializable] -> String
serializeAll as = intercalate ", " (map (\(Serializable a) -> serialize a) as)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment