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

标签 haskell ghc typeclass

我认为标题已经不言自明,但无论如何,这里有一个例子来说明我的观点:

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'

现在调用该函数将导致运行时错误。为什么这是一个警告,而不是编译时错误?有没有办法让它成为编译时错误?

最佳答案

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 的唯一方法编译器错误。

关于haskell - 为什么 GHC 只对部分实现的类发出警告,而不是错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29253477/

相关文章:

haskell - 使用 Nix,如何在启用分析的情况下指定 Haskell 依赖项?

haskell - Cabal Mac OS(雪豹)出错 - ld : unknown option: -no_pie

haskell - 的 是什么意思? Haskell 中的记录语法如何做?

haskell - 您可以对自定义数据类型使用特殊语法,例如在列表中吗?

haskell - 在 Haskell 中描述一般图形的类型类

haskell - 在 Haskell 中使用类型类作为可变参数模式

haskell - 省略 Happy 中的剩余输入(Haskell 的解析器生成器)

仿函数的 Haskell 类型推断

haskell - 安装Haskell时出错无法安装ghc

Haskell:默认约束类型