简体   繁体   English

对Haskell中的自定义数据类型感到困惑

[英]Confused about custom data types in Haskell

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. 我还希望能够使用Haskell的自然顺序对其进行排序。

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' . 它抛出以下错误: 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 Show instance to convert the type to a printable representation (a String ). 您需要一个Show实例将类型转换为可打印的表示( String )。 The easiest way to obtain one is to add 获得一个的最简单方法是添加

deriving Show

to the type definition. 到类型定义。

data Person = Person { 
    first_name :: String, 
    last_name :: String,   
    age :: Int }
      deriving (Eq, Ord, Show)

to get the most often needed instances. 获得最常需要的实例。

If you want a different Ord instance, as suggested in the comments, instead of deriving that (keep deriving Eq and Show unless you want different behaviour for those), provide an instance like 如果你想要一个不同的Ord实例,正如评论中所建议的那样,而不是派生它(继续导出EqShow除非你想要那些不同的行为),提供一个像

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 prefer, 或者如果您愿意,可以在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

That compares according to age first, then last name, and finally, if needed, first name. 根据年龄,然后是姓氏,最后,如果需要,比较名字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM