1

In the code below, I define an algebraic data type and I (attempt to) make it an instance of Show. However, I'm getting a compile-time error (included below). What am I doing wrong?

I believe I'm using the correct syntax (atleast as per this post). For context, I'm working Problem #13 in '99 Haskell Problems'

data RepeatType a = Multiple (Int, a) | Single a

instance Show RepeatType where
  show (Multiple (n,x)) = "(" ++ n ++ " " ++ show x ++ ")"
  show (Single x)       = show x

I'm getting the following compile-time error:

test.hs:3:15:
    Expecting one more argument to `RepeatType'
    In the instance declaration for `Show RepeatType'
Failed, modules loaded: none.

For example, the goal is for it to work as follows in GHCi:

ghci> Multiple (5,'C')
(5 C)
ghci> Single 'D'
D

EDIT: Sorry for the totally irrelevant post title - changed now.

0

1 Answer 1

11

Your problem is that RepeatType by itself is not really a type, it's a type constructor. Show can only be instantiated for "proper" types, e.g. RepeatType a. However, for this to work you need to promise that a itself will be an instance of Show, so you will end up with something like this:

instance (Show a) => Show (RepeatType a) where
  show (Multiple (n,x)) = "(" ++ show n ++ " " ++ show x ++ ")"
  show (Single x)       = show x

(Note: you will also need to call show on n in the first part of the definition, since you cannot concatenate Ints and Strings.)

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.