Skip to content

Instantly share code, notes, and snippets.

@dtchepak
Created January 15, 2012 09:47
Show Gist options
  • Save dtchepak/1615250 to your computer and use it in GitHub Desktop.
Save dtchepak/1615250 to your computer and use it in GitHub Desktop.
data Car = Car { make :: String, model :: String } deriving (Eq,Show)
-- Explicit implementation of Ord for Car
instance Ord Car where
compare (Car { make = aMake, model = aModel}) (Car { make = bMake, model = bModel}) =
if makeCompare == EQ then aModel `compare` bModel else makeCompare
where makeCompare = aMake `compare` bMake
-- Implementation over arbitrary number of field in record.
comp :: (Ord a) => [b -> a] -> b -> b -> Ordering
comp [] _ _ = EQ
comp (x:xs) a b = if (propCompare == EQ) then comp xs a b else propCompare
where aProp = x a
bProp = x b
propCompare = aProp `compare` bProp
{-
Ok, modules loaded: Main.
*Main> let a = Car "Toyota" "Prius"
*Main> let b = Car "Toyota" "Corolla"
*Main> let c = Car "Audi" "A4"
*Main> comp [make, model] a b
GT
*Main> comp [make, model] c a
LT
*Main> comp [make, model] c c
EQ
*Main> comp [make] a b
EQ
*Main> comp [make] a c
GT
-}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment