1
votes

Codes below are from Programming in Haskell by Hutton (p.101).

data Shape = Circle Float | Rect Float Float

square :: Float -> Shape
square n = Rect n n

area : Shape -> Float
area(Rect x y) = x * y

In ghci, if I type area(Rect 3 5), I get 15. But if I type square 5(thinking that I would get Rect 5 5 as a result), I get an error message:
"No instance for (Show Shape) arising from a use of ‘print’ In a stmt of an interactive GHCi command: print it".

Why is that?

1

1 Answers

3
votes

Behind the scenes, GHCi is trying to call print (square 5). Unfortunately this requires Shape to implement something called the Show typeclass. You can make the error go away by adding deriving Show to the end of the data Shape = Circle Float | Rect Float Float deriving Show.

There's a great section on the Show typeclass in Learn You a Haskell and a great answer on deriving in Stack Overflow.