Ambiguous type variable `p0' in the constraints

时间秒杀一切 提交于 2020-01-04 05:59:52

问题


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) 

回答1:


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


来源:https://stackoverflow.com/questions/8682364/ambiguous-type-variable-p0-in-the-constraints

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!