0
votes

Here is the piece of code:

import System.Environment 
myReverse :: [a] -> [a]
myReverse [] = []
main = print (myReverse [])

When I compile that with GHC I get the following error:

[1 of 1] Compiling Main ( problem5_myReverse.hs, problem5_myReverse.o ) problem5_myReverse.hs:6:8: No instance for (Show a0) arising from a use of print' The type variablea0' is ambiguous Possible fix: add a type signature that fixes these type variable(s) Note: there are several potential instances: instance Show Double -- Defined in GHC.Float' instance Show Float -- Defined inGHC.Float' instance (Integral a, Show a) => Show (GHC.Real.Ratio a) -- Defined in GHC.Real' ...plus 23 others In the expression: print (myReverse []) In an equation formain': main = print (myReverse [ ])

But when I change the signature from myReverse::[a]->[a] to myReverse::[Int]->[Int] the source code is compiled without any problems

Can somebody tell how can I keep the general signature [a] -> [a] but make it work for empty Integer lists?

1
main = print [] will evoke the exact same error. Your function has nothing to do with it. print needs a concrete type such as Int or [Int] or ... (anything of class Show). But all it has is [a] because the list is empty and its elements could potentially be of any type.n. 1.8e9-where's-my-share m.
As a side note, it actually does matter. The way [] prints is actually different if it has type [Char] than if it has type [Int], for instance.Carl

1 Answers

7
votes

From myReverse [] (or [] in general), it is not possible to for the type inferencer to infer to list element type because it's an empty list. If you explicitly call e.g. myReverse ([] :: [Int]), it'll be able to find a Show instance for the list so that it can convert it to string before printing.

This is because the Show instance for lists is defined with Show a => Show [a] meaning that [a] only has a Show instance for it if a has a Show instance for it. But there is no a to start with in the case of [].