任务:,我正在尝试创建一个自定义数据类型,并让它能够打印到控制台。我也希望能够用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)发布于 2012-04-11 22:50:10
您需要一个Show实例来将类型转换为可打印的表示形式( String)。最简单的获取方法是添加
deriving Show到类型定义。
data Person = Person {
first_name :: String,
last_name :: String,
age :: Int }
deriving (Eq, Ord, Show)来获取最需要的实例。
如果您想要一个不同的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或者在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这是根据年龄第一,然后姓氏,最后,如果需要,名字比较。
https://stackoverflow.com/questions/10115057
复制相似问题