我理解为了定义相同类型的不同实现,我们需要使用newtype
data Person = Person {
name :: String
, age :: Int
} deriving Show
class Describable a where describe :: a -> String
instance Describable Person where
describe person = name person ++ " (" ++ show (age person) ++ ")"
newtype AnotherPerson = AnotherPerson Person
但是,在相同字段名称的记录之间存在名称冲突的haskell问题
instance Describable AnotherPerson where
describe person = name person ++ " - " ++ show (age person)
<interactive>:79:65: error:
• Couldn't match expected type ‘Person’
with actual type ‘AnotherPerson’
• In the first argument of ‘name’, namely ‘person’
In the first argument of ‘(++)’, namely ‘name person’
In the expression: name person ++ " - " ++ show (age person)
我尝试使用pragma DuplicateRecordFields
,但它没有帮助。我们应该怎么做?
你这里没有任何重复的记录字段;唯一的记录字段是name
类型的age
和Person
。 AnotherPerson
类型不是记录,它没有记录字段。 AnotherPerson
“包裹”一个Person
值;它不会“继承”Person
类型的字段。
AnotherPerson
构造函数有一个Person
类型的(非记录)字段。您可以在AnotherPerson
上进行模式匹配以获得基础Person
值:
instance Describable AnotherPerson where
describe (AnotherPerson person) =
name person ++ " - " ++ show (age person)