简体   繁体   中英

Haskell basic Show instance for simple recursive datatype not working

i have a simple Problem. This Code looks perfectly fine to me.

main = do
      print("10-2")
      let a = L
      let b = E "abc" a
      print(a)
      print(b)


  data List a = L | E a (List a)

  instance (Show a) => Show (List a) where
      show L = "Empty"
      show (E a list) = (show a)++ (show list)

But it produces following error:

10-2.hs:5:5:
    No instance for (Show a0) arising from a use of `print'
    The type variable `a0' is ambiguous...

I cant find the Problem. Thanks for the Help!

In your function main, when you write let a = L , the type of a is just List a0 . When the compiler tries to know which version of the Show instance it has to use, all types fits, because a 's type is not fully defined. If you delete the line print a however, you will see that print b will work, because b 's type can only be List String , and the compiler knows exactly which version of show it has to use.

main = do
  print "10-2"
  let a = L
  let b = E "abc" a
  -- print a
  print b

Try writing print [] and you will see that the compiler gives you the same kind of error.

In ghci however, if you just type print L or print [] , it will not prompt an error. I don't know why this is happening.

It's the same error you will get if you try to compile this simple program:

main = print []

What? Haskell cannot print an empty list? That's correct, it cannot. That is, unless the type of the list element is known. It is not known at this case, so compilation fails. In order to see why, run these two programs:

main = print ([] :: [Int])
main = print ([] :: [Char])

The output is different, though the only difference between these programs is the type of an empty list.

However , if you try this same ambiguous program in ghci it will print [] just fine!

Prelude> let main = print []
Prelude> main
[]
Prelude>

This is because ghci has a slightly more liberal set of defaulting rules than ghc . So if you load your data type definition to ghci and say print L at the prompt, ghci will happily obey:

[1 of 1] Compiling Main             ( h.hs, interpreted )
Ok, modules loaded: Main.
*Main> print L
Empty
*Main>

As the others already said, you need to give your List a type, even if the data Constructor doesn't need it to create itself.

So Try out:

print (L :: List Int) 

or whatever you like to just print a your String of the Show Instance of (List a)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM