格拉斯哥Haskell编译器(GHC)为何在此报告多个类型错误?
Understanding GHC's Type Errors in Your Haskell Code
Let's break down the three type errors GHC 7.8.4 throws for your code, starting with the code itself:
module TypeErrors where f xs = [True | _ <- repeat 0] x = (x, x)
The First Error: Ambiguous Type Variable from the Literal 0
The error message No instance for (Num t0) arising from the literal ‘0’ The type variable ‘t0’ is ambiguous comes directly from the line repeat 0. Here's the breakdown:
- The
repeatfunction has the typea -> [a], so the literal0needs to belong to some type that implements theNumtypeclass (Haskell numeric literals are polymorphic by default:0 :: Num a => a). - But in your list comprehension, you're completely ignoring the elements of
repeat 0(using_as the pattern variable). There's no context anywhere in the code that tells GHC what specificNumtype to use for0—no function calls or type annotations that constrain it toInteger,Double, or any other concrete numeric type. - Normally, GHC has defaulting rules that pick a concrete type for ambiguous
Numvariables (likeIntegerorDouble), but when the module contains the invalid infinite type definition (line 3), GHC's type checking process gets interrupted before it can apply those defaults. When you comment out line 3, the defaulting rules kick in, so GHC picks a valid default type for0and the code compiles successfully.
The Second & Third Errors: Infinite Type from x = (x, x)
These errors come from an impossible type constraint that arises from the recursive definition. Let's walk through the type inference step by step:
- Suppose
xhas typet. - The right-hand side
(x, x)is a tuple where both elements arex, so its type is(t, t). - For the definition to be valid,
tmust equal(t, t)—this is an infinite recursive type. There's no finite, well-formed Haskell type that can satisfy this equality, so GHC rejects the definition with errors about unconstructible infinite types.
How to Fix These Errors
- Fixing the ambiguous type error: You can either explicitly annotate the type of
0to remove ambiguity, likerepeat (0 :: Integer), or enable theExtendedDefaultRulesGHC extension (add{-# LANGUAGE ExtendedDefaultRules #-}at the top of the module) to make GHC's defaulting rules apply in more edge cases. - Fixing the infinite type error: The definition
x = (x, x)is logically unevaluable (it's an infinite loop of self-references) and has no valid type. You'll need to replace it with a meaningful, non-recursive definition, likex = (1, "hello")or any other concrete tuple that doesn't reference itself.
内容的提问来源于stack exchange,提问作者Mark Wildon
相关产品推荐
相关产品推荐

