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

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.

Related

How to work around issue with ambiguity when monomorphic restriction turned *on*?

So, learning Haskell, I came across the dreaded monomorphic restriction, soon enough, with the following (in ghci):
Prelude> let f = print.show
Prelude> f 5
<interactive>:3:3:
No instance for (Num ()) arising from the literal `5'
Possible fix: add an instance declaration for (Num ())
In the first argument of `f', namely `5'
In the expression: f 5
In an equation for `it': it = f 5
So there's a bunch of material about this, e.g. here, and it is not so hard to workaround.
I can either add an explicit type signature for f, or I can turn off the monomorphic restriction (with ":set -XNoMonomorphismRestriction" directly in ghci, or in a .ghci file).
There's some discussion about the monomorphic restriction, but it seems like the general advice is that it is ok to turn this off (and I was told that this is actually off by default in newer versions of ghci).
So I turned this off.
But then I came across another issue:
Prelude> :set -XNoMonomorphismRestriction
Prelude> let (a,g) = System.Random.random (System.Random.mkStdGen 4) in a :: Int
<interactive>:4:5:
No instance for (System.Random.Random t0)
arising from the ambiguity check for `g'
The type variable `t0' is ambiguous
Possible fix: add a type signature that fixes these type variable(s)
Note: there are several potential instances:
instance System.Random.Random Bool -- Defined in `System.Random'
instance System.Random.Random Foreign.C.Types.CChar
-- Defined in `System.Random'
instance System.Random.Random Foreign.C.Types.CDouble
-- Defined in `System.Random'
...plus 33 others
When checking that `g' has the inferred type `System.Random.StdGen'
Probable cause: the inferred type is ambiguous
In the expression:
let (a, g) = System.Random.random (System.Random.mkStdGen 4)
in a :: Int
In an equation for `it':
it
= let (a, g) = System.Random.random (System.Random.mkStdGen 4)
in a :: Int
This is actually simplified from example code in the 'Real World Haskell' book, which wasn't working for me, and which you can find on this page: http://book.realworldhaskell.org/read/monads.html (it's the Monads chapter, and the getRandom example function, search for 'getRandom' on that page).
If I leave the monomorphic restriction on (or turn it on) then the code works. It also works (with the monomorphic restriction on) if I change it to:
Prelude> let (a,_) = System.Random.random (System.Random.mkStdGen 4) in a :: Int
-106546976
or if I specify the type of 'a' earlier:
Prelude> let (a::Int,g) = System.Random.random (System.Random.mkStdGen 4) in a :: Int
-106546976
but, for this second workaround, I have to turn on the 'scoped type variables' extension (with ":set -XScopedTypeVariables").
The problem is that in this case (problems when monomorphic restriction on) neither of the workarounds seem generally applicable.
For example, maybe I want to write a function that does something like this and works with arbitrary (or multiple) types, and of course in this case I most probably do want to hold on to the new generator state (in 'g').
The question is then: How do I work around this kind of issue, in general, and without specifying the exact type directly?
And, it would also be great (as a Haskell novice) to get more of an idea about exactly what is going on here, and why these issues occur..
When you define
(a,g) = random (mkStdGen 4)
then even if g itself is always of type StdGen, the value of g depends on the type of a, because different types can differ in how much they use the random number generator.
Moreover, when you (hypothetically) use g later, as long as a was polymorphic originally, there is no way to decide which type of a you want to use for calculating g.
So, taken alone, as a polymorphic definition, the above has to be disallowed because g actually is extremely ambiguous and this ambiguity cannot be fixed at the use site.
This is a general kind of problem with let/where bindings that bind several variables in a pattern, and is probably the reason why the ordinary monomorphism restriction treats them even stricter than single variable equations: With a pattern, you cannot even disable the MR by giving a polymorphic type signature.
When you use _ instead, presumably GHC doesn't worry about this ambiguity as long as it doesn't affect the calculation of a. Possibly it could have detected that g is unused in the former version, and treated it similarly, but apparently it doesn't.
As for workarounds without giving unnecessary explicit types, you might instead try replacing let/where by one of the binding methods in Haskell which are always monomorphic. The following all work:
case random (mkStdGen 4) of
(a,g) -> a :: Int
(\(a,g) -> a :: Int) (random (mkStdGen 4))
do (a,g) <- return $ random (mkStdGen 4)
return (a :: Int) -- The result here gets wrapped in the Monad

GHCI can't infer Eq class at compile time, but does fine at runtime?

Sorry for the confusing title. I am writing a parser combinator library in Haskell for fun. Here are all (I think!) the relevant type annotations and definitions:
data Parser a = Parser (State -> Reply a)
parse :: Parser a -> [Char] -> Either ParseError a
nil :: Parser [a]
nil = Parser $ \state -> Ok [] state
Basically, the parse function applies the function that a Parser wraps around to the current state, and if the parse is successful, wraps the result in an Either. The nil parser takes a state and returns a successful parse of the empty list. So we should have,
parse nil "dog" == Right []
In fact, if I just load the module where all these live, then it compiles and this evaluates to True.
I'm actually trying to run some QuickCheck tests on the library, though, so I wrote this:
import Parsimony
import Test.QuickCheck
prop_nil :: [Char] -> Bool
prop_nil xs = parse nil xs == Right []
This fails to compile! It throws the following error:
No instance for (Eq a0) arising from a use of `=='
The type variable `a0' is ambiguous
At this point I am mostly just confused why an expression could work fine when evaluated, but fail to compile in a parametrized version.
Since nil is polymorphic and Right [] is also polymorphic GHC has an expression of type Bool, but with some unbound type variable in the middle. GHC keels over and dies since it doesn't know what concrete type to use. GHCi for better or worse, will infer [()] or something like that because of its defaulting rules. This is one of ghci's weird quirks, it will automagically default type variables.
To fix this, simply for force the binding of a manually
-- It's important that whatever you force it to actually is comparable
-- eg there should be an instance like
instance Eq ParseError where
-- Otherwise you're kinda stuck.
prop_nil xs = parse nil xs == (Right xs :: Either ParseError String)
PS I like the name Parsimony for a parser library, good luck!
The problem is that the type of nil is Parser [a]. So parse nil xs is of type Either ParseError [a]. Right [] is most generally of type Either l [a]; comparing it to parse nil xs forces the l to be ParseError, but the type in the list is still completely unconstrained. Without any more context it remains fully polymorphic; that a isn't necessarily a member of the Eq type class and even if it is there's no way to know which instance to use for the implementation of ==, and so it isn't valid to invoke == on those two terms.
In a realistic program, you'd likely be saved from this by the fact that you'd use the result for something, which would force that particular occurrence to be consistent with whatever you use it for. That would probably be some concrete type which has an implementation of Eq.
When you talk about loading the module, I presume you mean in the GHCI interpreter. GHCI adds some additional defaulting rules. In particular it will tend to default unconstrained type variables (which aren't the type of a top level function) to (), so that it doesn't have to complain about ambiguous type variables quite so often.
An interactive session in GHCi tends to encounter ambiguous type variable far more often than realistic modules compiled in full, because it has to compile small snippets mostly independently. GHCi has extended defaulting rules to make those work a lot more often (though it often only delays the error to the next reference when the user was expecting a different type, and the difference between GHCi and GHC often causes confusion).
Test snippets can suffer from a similar problem. If you're testing polymorphic functions you often don't constrain some of the types sufficiently for type inference to work, as you would in real purposeful usage of the function. But without the extended defaulting rules of GHCi, this problem manifests as an actual ambiguous type error at the location of the problem, rather than masking it by arbitrarily picking a type.
To fix this, you just need to add a type annotation to fix the type of the list. Either declare the full type of parse nil xs or Right [], just declare the type of the empty list literal on the right hand side. Sometihng like this should do the trick:
prop_nil :: [Char] -> Bool
prop_nil xs = parse nil xs == Right ([] :: [Int])
Another way would be to avoid the Eq constraint in the first place:
prop_nil xs = either (const False) null (parse nil xs)
or, more explicit
prop_nil xs = case parse nil xs of
Right [] -> True
_ -> False

haskell - "Ambiguous type variable" after qualified import

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.

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.

Resources