haskell - "Ambiguous type variable" after qualified import - haskell

I have a little problem to understand an error message in haskell.
For instance:
import qualified Data.Map as M
test = M.empty
This code runs as it should do without getting any error message.
The output looks like:
*Main> test
fromList []
But if I try something like that
import qualified Data.Map as M
test = do print M.empty
I get an error message like this
Ambiguous type variable `k0' in the constraint:
(Show k0) arising from a use of `print'
Probable fix: add a type signature that fixes these type variable(s)
In a stmt of a 'do' block: print M.empty
In the expression: do { print M.empty }
In an equation for `test': test = do { print M.empty }
So I think it has something to do with the print statement.
But if I try it in the console (ghci)
Prelude Data.Map> print empty
fromList []
everything works fine.
So I hope someone can explain me where the problem is.
Thanks in advance.

This code runs as it should do without getting any error message.
In a source file, it shouldn't.
import qualified Data.Map as M
test = M.empty
The inferred type of test is Ord k => Map k a, a polymorphic type with a constrained type variable. Since test is not a function and has no type signature, by the monomorphism restriction, its type must be made monomorphic by resolving the constrained type variables to a default type. Since the only constraint here is Ord, the defaulting rules forbid that type variable to be defaulted (there must be at least one numeric constraint for defaulting to be allowed).
Thus, compilation is required to fail by the language standard.
In ghci, however, there are extended defaulting rules that allow to default the type. If you want to print test, a further Show constraint is introduced on both type variables, and ghci defaults the type of test to Map () () when asked to print it.

This is because Data.Map.empty has the type Map k a. A map of keys of type k to values, type a.
print on the other hand has the type print :: Show a => a -> IO (), which means that it can only display types that are instances of Show, while M.empty has type Map k a, has no such constraint. It can be any type k or a -- it is not required to be able to show them.
So, basically, print doesn't know what type it's being asked to display.
As for why it works in ghci; I'm not entirely sure. Maybe one of the resident Haskell wizards can shed some light on that.

Related

Why such different behaviour with `Ambiguous type..` error (in ghci)?

This example works with ghci, load this file:
import Safe
t1 = tailMay []
and put in ghci:
> print t1
Nothing
But if we add analogous definition to previous file, it doesn't work:
import Safe
t1 = tailMay []
t2 = print $ tailMay []
with such error:
* Ambiguous type variable `a0' arising from a use of `print'
prevents the constraint `(Show a0)' from being solved.
Probable fix: use a type annotation to specify what `a0' should be.
These potential instances exist:
instance Show Ordering -- Defined in `GHC.Show'
instance Show Integer -- Defined in `GHC.Show'
instance Show a => Show (Maybe a) -- Defined in `GHC.Show'
...plus 22 others
That is 3rd sample for ghc with the same error:
import Safe
t1 = tailMay
main = do
print $ t1 []
print $ t1 [1,2,3]
Why? And how to fix the second sample without explicit type annotation?
The issue here is that tailMay [] can generate an output of type Maybe [a] for any a, while print can take an input of type Maybe [a] for any a (in class Show).
When you compose a "universal producer" and a "universal consumer", the compiler has no idea about which type a to pick -- that could be any type in class Show. The choice of a could matter since, in principle, print (Nothing :: Maybe [Int]) could print something different from print (Nothing :: Maybe [Bool]). In this case, the printed output would be the same, but only because we are lucky.
For instance print ([] :: [Int]) and print ([] :: [Char]) will print different messages, so print [] is ambiguous. Hence, GHC reject it, and requires an explicit type annotation (or a type application # type, using an extension).
Why, then, such ambiguity is accepted in GHCi? Well, GHCi is meant to be used for quick experiments, and as such, as a convenience feature, it will try hard to default these ambiguous a. This is done using the extended defaulting rules, which could (I guess) in principle be turned on in GHC as well by turning on that extension.
This is, however, not recommended since sometimes the defaulting rule can choose some unintended type, making the code compile but with an unwanted runtime behavior.
The common solution to this issue is using an annotation (or # type), because it provides more control to the programmer, makes the code easier to read, and avoids surprises.

Ambiguous Types, and Defaults for Overloaded Numeric Operations

import Data.Dynamic
default(Integer,Double)
a :: Num a => a
a = 5
-- show :: Show a => a -> String
-- toDyn :: Typeable a => a -> Dynamic
main :: IO ()
-- main = print $ show a -- *** THIS LINE WORKS WELL
main = print $ toDyn a -- *** THIS LINE LEADS TO AN AMBIGUOUS TYPE ERROR
I don't understand why the first "main" version works, and not the second.
Is there someone who can help me ?
Thanks in advance for your reply.
From the Haskell report:
In situations where an ambiguous type is discovered, an ambiguous type variable, v, is defaultable if:
v appears only in constraints of the form C v, where C is a class, and
at least one of these classes is a numeric class, (that is, Num or a subclass of Num), and
all of these classes are defined in the Prelude or a standard library
Your example fails because unlike Show, Typeable is not one of the classes specified in the third point, so no defaulting is performed.

Ambiguous type variable `p0' in the constraints

I get the error
Ambiguous type variable `p0' in the constraints:
(Show p0) arising from a use of `print' at cwqr_0003.hs:31:6-10
(Ord p0) arising from a use of `PSQ.lookup'
from the code below.
I have no idea how to analyze this. Could this be a problem in GHC or in one of the modules?
If I try putStr in place of print then I get an error related to the expected type being a string rather then maybe p0. When I try fromMaybe it gives me an error related to the default value literal zero that I send to fromMaybe
import qualified Data.PSQueue as PSQ
import Data.Maybe
import Data.Label
import Control.Category
import Prelude hiding ((.))
--some tested code omitted here
let r = PSQ.lookup test' q
--putStr (show (r :: String))
print (r)
The error message actually means exactly what it says: You have an ambiguous type. How does that happen? Usually, because you have something that produces a polymorphic result, then apply a function that takes a polymorphic argument to that result, such that the intermediate value's type is unknown.
In simple polymorphic types, the ambiguity doesn't matter: If you produce a list of something, then take the length, we don't need to know what the type of the list elements is.
If the ambiguity involves using a type class such as Show, however--which print does--GHC is stuck, because it has no way to know what instance it should pick.
Sometimes this can also arise because a particular definition is forced to be monomorphic (unless you specifically say otherwise), which forces a single type to be chosen instead of retaining the polymorphism. I suspect that might be your problem, but I can't tell without the context you've removed.
To illustrate the latter, the following definition:
foo = print
...with no type signature, causes an error like this:
Test.hs:12:7:
Ambiguous type variable `a0' in the constraint:
(Show a0) arising from a use of `print'
Possible cause: the monomorphism restriction applied to the following:
foo :: a0 -> IO () (bound at Test.hs:12:1)
Probable fix: give these definition(s) an explicit type signature
or use -XNoMonomorphismRestriction
In the expression: print
In an equation for `foo': foo = print

How do I resolve this compile error: Ambiguous type variable `a1' in the constraint

One could think of this case as follows:
The application dynamically loads a module, or there is a list of functions from which the user chooses, etc. We have a mechanism for determining whether a certain type will successfully work with a function in that module. So now we want to call into that function. We need to force it to make the call. The function could take a concrete type, or a polymorphic one and it's the case below with just a type class constraint that I'm running into problems with it.
The following code results in the errors below. I think it could be resolved by specifying concrete types but I do not want to do that. The code is intended to work with any type that is an instance of the class. Specifying a concrete type defeats the purpose.
This is simulating one part of a program that does not know about the other and does not know the types of what it's dealing with. I have a separate mechanism that allows me to be sure that the types do match up properly, that the value sent in really is an instance of the type class. That's why in this case, I don't mind using unsafeCoerce. But basically I need a way to tell the compiler that I really do know it's ok and do it anyway even though it doesn't know enough to type check.
{-# LANGUAGE ExistentialQuantification, RankNTypes, TypeSynonymInstances #-}
module Main where
import Unsafe.Coerce
main = do
--doTest1 $ Hider "blue"
doTest2 $ Hider "blue"
doTest1 :: Hider -> IO ()
doTest1 hh#(Hider h) =
test $ unsafeCoerce h
doTest2 :: Hider -> IO ()
doTest2 hh#(Hider h) =
test2 hh
test :: HasString a => a -> IO ()
test x = print $ toString x
test2 :: Hider -> IO ()
test2 (Hider x) = print $ toString (unsafeCoerce x)
data Hider = forall a. Hider a
class HasString a where
toString :: a -> String
instance HasString String where
toString = id
Running doTest1
[1 of 1] Compiling Main ( Test.hs, Test.o )
Test.hs:12:3:
Ambiguous type variable `a1' in the constraint:
(HasString a1) arising from a use of `test'
Probable fix: add a type signature that fixes these type variable(s)
In the expression: test
In the expression: test $ unsafeCoerce h
In an equation for `doTest1':
doTest1 hh#(Hider h) = test $ unsafeCoerce h
Running doTest2
[1 of 1] Compiling Main ( Test.hs, Test.o )
Test.hs:12:3:
Ambiguous type variable `a1' in the constraint:
(HasString a1) arising from a use of `test'
Probable fix: add a type signature that fixes these type variable(s)
In the expression: test
In the expression: test $ unsafeCoerce h
In an equation for `doTest1':
doTest1 hh#(Hider h) = test $ unsafeCoerce h
I think it could be resolved by specifying concrete types but I do not want to do that.
There's no way around it though with unsafeCoerce. In this particular case, the compiler can't infer the type of unsafeCoerce, because test is still to polymorphic. Even though there is just one instance of HasString, the type system won't use that fact to infer the type.
I don't have enough information about your particular application of this pattern, but I'm relatively sure that you need to rethink the way you use the type system in your program. But if you really want to do this, you might want to look into Data.Typeable instead of unsafeCoerce.
Modify your data type slightly:
data Hider = forall a. HasString a => Hider a
Make it an instance of the type class in the obvious way:
instance HasString Hider where
toString (Hider x) = toString x
Then this should work, without use of unsafeCoerce:
doTest3 :: Hider -> IO ()
doTest3 hh = print $ toString hh
This does mean that you can no longer place a value into a Hider if it doesn't implement HasString, but that's probably a good thing.
There's probably a name for this pattern, but I can't think what it is off the top of my head.

How to use quickcheck in main

I am writing a test for a binary search function I wrote.
module Tests where
import Data.List (sort)
import Test.QuickCheck
import BinarySearch (binarySearch)
prop_equals_elem x xs = (binarySearch x $ sort xs) == (x `elem` xs)
args = Args {replay = Nothing, maxSuccess = 200, maxDiscard=200, maxSize=200, chatty = False}
main = do
quickCheck (prop_equals_elem :: (Ord a) => a -> [a] -> Bool)
It works well using quickCheck in ghci but when I try to run main it gives the error
Tests.hs:12:5:
Ambiguous type variable `a0' in the constraints:
(Arbitrary a0) arising from a use of `quickCheckWith'
at Tests.hs:12:5-18
(Show a0) arising from a use of `quickCheckWith'
at Tests.hs:12:5-18
(Ord a0) arising from an expression type signature
at Tests.hs:12:26-72
Why does this not work in main but does in ghci?
This is likely caused by the extended defaulting rules in GHCi.
When testing a function like this, you need to use a concrete element type. GHCi will default the element type to () because of the extended rules, but this will not happen when compiling the code normally, so GHC is telling you that it cannot figure out which element type to use.
You can for example use Int instead for the test. () is pretty useless for testing this function, as all elements would be the same.
quickCheck (prop_equals_elem :: Int -> [Int] -> Bool)
If it works for Int, it should work for any type due to parametricity.
When you run a QuickCheck test, QuickCheck needs to know how to generate data. Here, you've told it only that your code should work with an arbitrary type of the Ord type class, which isn't enough for it to start testing. Hence the error about ambiguous type classes.
If you just need an arbitrary Ord instance, as it appears here, then something like Int would be a good choice for your testing. It's a simple type with a linear order. So try fixing your type to Int in main, as in:
quickCheck (prop_equals_elem :: Int -> [Int] -> Bool)
As for why it works in GHCi, the answer is defaulting. GHCi defaults type variables to () whenever possible, just to avoid giving spurious errors in situations where you really don't care about a value. Actually that's an awful choice: you won't test anything interesting by only testing with the () type! So again, the explicit type signature is better.

Resources