Confused about user data types in Haskell

Task: I am trying to create a custom data type and be able to print to the console. I also want to be able to sort it using Haskell's natural ordering.

Problem: Write now, I can not get this code to compile. It throws the following error: No instance for (Show Person) arising from a use of 'print' .

What I still have:

 -- 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) 
+6
source share
1 answer

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.

+8
source

Source: https://habr.com/ru/post/912980/


All Articles