You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

格拉斯哥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 repeat function has the type a -> [a], so the literal 0 needs to belong to some type that implements the Num typeclass (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 specific Num type to use for 0—no function calls or type annotations that constrain it to Integer, Double, or any other concrete numeric type.
  • Normally, GHC has defaulting rules that pick a concrete type for ambiguous Num variables (like Integer or Double), 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 for 0 and 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 x has type t.
  • The right-hand side (x, x) is a tuple where both elements are x, so its type is (t, t).
  • For the definition to be valid, t must 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 0 to remove ambiguity, like repeat (0 :: Integer), or enable the ExtendedDefaultRules GHC 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, like x = (1, "hello") or any other concrete tuple that doesn't reference itself.

内容的提问来源于stack exchange,提问作者Mark Wildon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:04:37