如何在haskell中实现相同记录类型的不同实现?

问题描述 投票:3回答:1

我理解为了定义相同类型的不同实现,我们需要使用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,但它没有帮助。我们应该怎么做?

haskell typeclass
1个回答
7
投票

你这里没有任何重复的记录字段;唯一的记录字段是name类型的agePersonAnotherPerson类型不是记录,它没有记录字段。 AnotherPerson“包裹”一个Person值;它不会“继承”Person类型的字段。

AnotherPerson构造函数有一个Person类型的(非记录)字段。您可以在AnotherPerson上进行模式匹配以获得基础Person值:

instance Describable AnotherPerson where
  describe (AnotherPerson person) =
    name person ++ " - " ++ show (age person)
© www.soinside.com 2019 - 2024. All rights reserved.