2

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
  • 1
    What error do you get? Please edit your question to include this important detail. Commented Sep 8, 2018 at 16:54

1 Answer 1

3
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.

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

4 Comments

Thank you! So why isn't LinkedList a type?
@OmarKahol Beacuse it lacks an argument. It is a constructor of kind * -> *, i.e. (roughly) a function from types to types, and we need to pass it an argument to get a type.
@OmarKahol LinkedList is a "type-level function" which produces types. It's not a type in the same way that (* 5) isn't a number, but if you pass it a number you get a number back.
@OmarKahol: You can learn more about kinds with the :kind command in GHCi. :kind Show gives * -> Constraint because Show is a typeclass that takes a type of kind * (a “base type”, one that contains values) and returns a constraint; :kind LinkedList gives * -> * because LinkedList is a type constructor that takes a type of kind * and produces a type, also of kind *. So you can’t write Show LinkedList because * and * -> * don’t match—it’s a kind error, which is like a type error at the type level. * can also be written as Type (imported from GHC.Types).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.