gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 02:12:17 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com