1
votes

I am trying to wrap my mind around classes and data structures in Haskell, specifically declaring a type instance of it. I can get it to work with some classes and data types but not all of them so I must be missing something. Specifically I have the following data declaration:

data LinkedList a = End | Link a (LinkedList a)

I want to declare an instance of Show for that type so that the output looks something close to "el1, el2, el3, el4, ..."

instance Show LinkedList where
    show (End) = "."
    show (Link a b) = show a ++ "," ++ show b

As expected this doesn't work... Any idea why? I think I understand what "data" and "type" mean but I am not sure whether I am comfortable with classes and instances. Thank you

1
What error do you get? Please edit your question to include this important detail.Code-Apprentice

1 Answers

2
votes
instance Show LinkedList where

LinkedList is not a type, LinkedList a is a type. Correcting that, we get

instance Show (LinkedList a) where

Then , we get another error because we call show on values of type a. We need to require that a belongs to class Show, too.

instance Show a => Show (LinkedList a) where

This should now work.