为什么 GHC 只对部分实现的 类 发出警告而不是错误?

Why does GHC only warn on partial implemented classes, and not error?

我认为这个标题已经是不言自明的了,但这里还是有一个例子来说明我的观点:

class Foo a where
    someFunction :: a -> a -> Bool

instance Foo Bool

当我编译这个时,编译器给出警告:

Warning:
    No explicit method or default declaration for `someFunction'
    in the instance declaration for `Foo Bool'

调用该函数现在将导致运行时错误。为什么这是警告,而不是 compile-time 错误?有什么办法可以让这个变成 compile-time 错误吗?

GHC documentation 提供了一个警告就足够的示例:

-fwarn-missing-methods:

This option is on by default, and warns you whenever an instance declaration is missing one or more methods, and the corresponding class declaration has no default declaration for them.

The warning is suppressed if the method name begins with an underscore. Here's an example where this is useful:

class C a where
  _simpleFn :: a -> String
  complexFn :: a -> a -> String
  complexFn x y = ... _simpleFn ...

The idea is that: (a) users of the class will only call complexFn; never _simpleFn; and (b) instance declarations can define either complexFn or _simpleFn.

The MINIMAL pragma can be used to change which combination of methods will be required for instances of a particular class. See Section 7.20.5, “MINIMAL pragma”.

这就是缺少方法不会导致错误但会导致警告的原因。如果你想让警告致命,使用 -Werror。由于没有 -ferr-missing-methods-Werror 是使 -fwarn-missing-methods 成为编译器错误的唯一方法。