Consider the following function:
foo :: Show a => Maybe a -> [Char]
foo (Just x) = show x
foo Nothing = "Nothing"
Then I try to use this function:
bar :: [Char]
bar = foo Nothing
The argument that has been passed to foo
is of type Maybe a
where a
is not specified, and indeed we don't care about a
, because we use only the case of foo
for the Nothing
. But the GHC claims to provide the concrete type:
Ambiguous type variable
a0
arising from a use offoo
prevents the constraint(Show a0)
from being solved. Probable fix: use a type annotation to specify whata0
should be.
GHC hints to specify the type. So the only fix I see there is to create a fake type which has an instance of Show
type class:
{-# LANGUAGE EmptyDataDecls, KindSignatures #-}
{-# OPTIONS_GHC -fno-warn-missing-methods #-}
data Dummy :: *
instance Show Dummy
bar :: [Char]
bar = foo (Nothing :: Maybe Dummy)
foo :: Show a => Maybe a -> [Char]
foo (Just x) = show x
foo Nothing = "Nothing"
It works, but seems to be pretty straightforward. But the real reason why I don't like this solution is because for my purposes this code is automatically generated from some meta data, which doesn't provide information about which particular polymorph type must be specified as Dummy
(there are may be user data types with more than one parameters). So I wonder, is there any way to tell GHC, that if the type is not specified, this type doesn't matter?
foo (Nothing :: Maybe ())
should be ok. – leftaroundabout