To convert a type to a printable representation (a String
), you need an instance of Show
. The easiest way to get this is to add
deriving Show
to determine the type.
data Person = Person { first_name :: String, last_name :: String, age :: Int } deriving (Eq, Ord, Show)
to get the most commonly used instances.
If you need another instance of Ord
, as suggested in the comments, instead of getting it (continue to output Eq
and Show
, unless you need other behavior for them), specify an instance of type
instance Ord Person where compare p1 p2 = case compare (age p1) (age p2) of EQ -> case compare (last_name p1) (last_name p2) of EQ -> compare (first_name p1) (first_name p2) other -> other unequal -> unequal
or use pattern matching in the definition of compare
, if you like,
compare (Person first1 last1 age1) (Person first2 last2 age2) = case compare age1 age2 of EQ -> case compare last1 last2 of EQ -> compare first1 first2 other -> other unequal -> unequal
This is compared by age first, then by last name and, finally, if necessary, by first name.
source share