我理解为我们需要使用相同类型的不同实现 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
Run Code Online (Sandbox Code Playgroud)
但是,在相同字段名称的记录之间存在名称冲突的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)
Run Code Online (Sandbox Code Playgroud)
我尝试使用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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
65 次 |
| 最近记录: |