Alan
Alan

Reputation: 2639

Printing new types in Haskell

I'm following a tutorial to create a new type. This is my code:

data Shape = Circle Float Float Float | Rectangle Float Float Float Float

When I load the file with ghci and I type:

Circle 10 20 5

It prints this:

<interactive>:29:1:
    No instance for (Show Shape) arising from a use of ‘print’
    In a stmt of an interactive GHCi command: print it

How can I solve this?

Upvotes: 1

Views: 279

Answers (2)

Alan
Alan

Reputation: 2639

I solved it typing this in the interpreter:

:s -u

Upvotes: 0

Thomas M. DuBuisson
Thomas M. DuBuisson

Reputation: 64740

The show function has type:

show :: Show a => a -> String

Which means it only works on things with a Show instances. You can make your types an instance of the Show class by either manually defining an instance or letting the compiler automatically derive one:

data Shape = Circle Float Float Float | Rectangle Float Float Float Float
  deriving (Show)

or

instance Show Shape where
    show (Circle a b c) = "Circle " ++ show a ++ " " ++ show b ++ " " ++ show c
    show (Rectangle a b c d) = ...

Upvotes: 10

Related Questions