The task: I am trying to create a custom data type and have it able to print to the console. I also want to be able to sort it using Haskell’s natural ordering.
The issue: Write now, I can’t get this code to compile. It throws the following error: No instance for (Show Person) arising from a use of 'print'.
What I have so far:
-- Omitted working selection-sort function
selection_sort_ord :: (Ord a) => [a] -> [a]
selection_sort_ord xs = selection_sort (<) xs
data Person = Person {
first_name :: String,
last_name :: String,
age :: Int }
main :: IO ()
main = print $ print_person (Person "Paul" "Bouchon" 21)
You need a
Showinstance to convert the type to a printable representation (aString). The easiest way to obtain one is to addto the type definition.
to get the most often needed instances.
If you want a different
Ordinstance, as suggested in the comments, instead of deriving that (keep derivingEqandShowunless you want different behaviour for those), provide an instance likeor use pattern matching in the definition of
compareif you prefer,That compares according to age first, then last name, and finally, if needed, first name.