Take the 2-minute tour ×

I try to create an own list type in haskell but, my implementation contains errors. What is the proper way to do this nice. Please explain me a bit. Thank you.

My code:

data List a = EmptyList | ListElement a (List a) 

instance (Show a) => Show (List a) where
        show = showList'

showList' EmptyList = showString "[]"
showList' (ListElement a EmptyList) = show a
showList' (ListElement a b) = show a ++ show " " ++ showList' b

Error code:

[1 of 1] Compiling Main             ( tipusok.hs, interpreted )

    Couldn't match expected type `Prelude.String -> Prelude.String'
                with actual type `[Char]'
    Expected type: ShowS
      Actual type: Prelude.String
    In the return type of a call of `show'
    In the expression: show a
Failed, modules loaded: none.
share|improve this question
add comment

2 Answers

up vote 3 down vote accepted
showList' EmptyList = showString "[]"

The type of showString is String -> ShowS. ShowS is a type synonym for String -> String, so the result of showString "[]" is the function that prepends the string "[]" to its argument. Since you gave no type signature, that equation determines what type is inferred for the function, but the other equations don't match that type.

You probably wanted simply

showList' EmptyList = "[]"
share|improve this answer
:) it's working, thank you –  flatronka May 21 '12 at 20:22
add comment

Your composition of show functions is incorrect. I think you mean to interpolate values.

showList' (ListElement a b) = show a . showChar ' ' . show b

should be something like:

showList' (ListElement a b) = show a ++ " " ++ showList' b
share|improve this answer
thanks, this recursive call is mandatory, i made an edit with the new error message –  flatronka May 21 '12 at 20:08
showChar does not return a String. I think you mean to use a whitespace literal? –  Don Stewart May 21 '12 at 20:09
thanks, i made an edit again, but it's still don't work –  flatronka May 21 '12 at 20:13
Get rid of the showString, showList' EmptyList = "[]". –  Vitus May 21 '12 at 20:14
thank you, for your advices, it's working –  flatronka May 21 '12 at 20:22
add comment

Your Answer


