任务:我正在尝试创建自定义数据类型,并使其能够打印到控制台.我还希望能够使用Haskell的自然顺序对其进行排序.
问题:现在写,我无法编译这段代码.它抛出以下错误:No instance for (Show Person) arising from a use of 'print'.
到目前为止我所拥有的:
-- 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)
Run Code Online (Sandbox Code Playgroud)
您需要一个Show实例将类型转换为可打印的表示(a String).获得一个的最简单方法是添加
deriving Show
Run Code Online (Sandbox Code Playgroud)
到类型定义.
data Person = Person {
first_name :: String,
last_name :: String,
age :: Int }
deriving (Eq, Ord, Show)
Run Code Online (Sandbox Code Playgroud)
获得最常需要的实例.
如果你想要一个不同的Ord实例,如评论中所建议的那样,而不是派生它(继续推导Eq,Show除非你想要那些不同的行为),提供一个像
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
Run Code Online (Sandbox Code Playgroud)
或者在compare你喜欢的定义中使用模式匹配,
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
Run Code Online (Sandbox Code Playgroud)
根据年龄,然后是姓氏,最后,如果需要,比较名字.