(Show Company) 没有因使用“打印”而产生的实例

No instance for (Show Company) arising from a use of `print'

我有以下代码

module Main where
data Company = C [Dept]
data Dept = D Name Manager [SubUnit]
data SubUnit = PU Employee | DU Dept
data Employee = E Person Salary
data Person = P Name Address
data Salary = S Float
type Manager = Employee
type Name = String
type Address = String

genCom :: Company
genCom = C [D "Research" ralf [PU joost, PU marlow], D "Strategy" blair []]
ralf, joost, marlow, blair :: Employee
ralf = E (P "Ralf" "Amsterdam") (S 8000)
joost = E (P "Joost" "Amsterdam") (S 1000)
marlow = E (P "Marlow" "Cambridge") (S 2000)
blair = E (P "Blair" "London") (S 100000)

main = print $ genCom

但是我收到以下错误消息

* No instance for (Show Company) arising from a use of `print'
* In the expression: print $ genCom
  In an equation for `main': main = print $ genCom

输出对象的最佳方式是什么?

您需要为该类型定义 Show typeclass since print :: Show a => a -> IO (). If the type is a member of the Show typeclass, the show :: Show a => a -> String 方法的实例。 show有点类似于Java/C#中的toString/ToString等:它是一种将对象转换为String的方法。

您可以创建自定义实例,但最简单的方法可能是让编译器自动派生实例。您可以通过添加 ... <b>deriving Show</b> 到您定义的数据类型来实现,因此:

data Company = C [Dept] <strong>deriving Show</strong>
data Dept = D Name Manager [SubUnit] <strong>deriving Show</strong>
data SubUnit = PU Employee | DU Dept <strong>deriving Show</strong>
data Employee = E Person Salary <strong>deriving Show</strong>
data Person = P Name Address <strong>deriving Show</strong>
data Salary = S Float <strong>deriving Show</strong>