[英]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.