在another question的解决方案中,我提出了以下代码,其类型检查很好:
import Control.Applicative
import Data.Foldable
tryCombination :: Alternative f => Int -> Int -> f (Int,Int)
tryCombination x y
| x * y == 20 = pure (x,y)
| otherwise = empty
result :: Alternative f => f (Int,Int)
result = asum [tryCombination x y | x <- [1..5], y <- [1..5]]
但是,当我从result
中删除类型签名时,ghc告诉我有关模糊类型变量的信息:
No instance for (Alternative f0) arising from a use of ‘asum’
The type variable ‘f0’ is ambiguous
Relevant bindings include
result :: f0 (Int, Int) (bound at BreakLoop.hs:12:1)
Note: there are several potential instances:
...
看起来ghc几乎完全推断出了正确的类型。那么,为什么这个推论不能完全完成呢?
当我使用以下部分类型签名时,我看到的错误消息甚至更奇怪:
result :: Alternative f => f _
消息是:
No instance for (Alternative f) arising from a use of ‘asum’
Possible fix:
add (Alternative f) to the context of
the inferred type of result :: f (Int, Int)
...
这种行为是否有任何合理的解释,还是只是一个错误?