[英]Confused about custom data types in Haskell
任务:我正在尝试创建自定义数据类型,并使其能够打印到控制台。 我还希望能够使用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)
您需要一个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
根据年龄,然后是姓氏,最后,如果需要,比较名字。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.