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

Viewed 67

I have the following code

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

However I get the following error message

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

What would be the best way to output my object?

1 Answers

You need to make the type an instance of the Show typeclass since print :: Show a => a -> IO (). If the type is a member of the Show typeclass, the show :: Show a => a -> String method is defined for that type. show is a bit similar to toString/ToString in Java/C#, etc.: it is a way to convert an object to a String.

You can make a custom instance, but the easiest way to do this is probably to let the compiler derive the instance automatically. You do this by adding … deriving Show to the data types you define, so:

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