"实例(Num a)=> YesNo a where"代码行的例外情况

And*_*man 2 haskell

这很好用:

class YesNo a where
    yesNo :: a-> Bool

instance YesNo Bool where
    yesNo True = True
    yesNo _ = False

instance YesNo [a] where
    yesNo [] = False
    yesNo _ = True

instance YesNo (Maybe a) where
    yesNo Nothing = False
    yesNo _ = True
Run Code Online (Sandbox Code Playgroud)

但是我收到代码错误:

instance (Num a) => YesNo a where -- error is here
    yesNo 0 = False
    yesNo _ = True
Run Code Online (Sandbox Code Playgroud)

异常消息:

ghci> :l src
[1 of 1] Compiling Main             ( src.hs, interpreted )

src.hs:16:21:
    Illegal instance declaration for `YesNo a'
      (All instance types must be of the form (T a1 ... an)
       where a1 ... an are *distinct type variables*,
       and each type variable appears at most once in the instance head.
       Use FlexibleInstances if you want to disable this.)
    In the instance declaration for `YesNo a'
Failed, modules loaded: none.
ghci>
Run Code Online (Sandbox Code Playgroud)

我做错了什么?

Mat*_*hid 5

看起来你正试图让它成为一个实例的每个类型Num自动成为的一个实例YesNo.

不幸的是,你做不到.

您只能为特定类型声明实例.所以你可以为Intor 声明一个实例Double,但你不能为"every Num" 声明一个实例.

  • 注意,您可以使用`DefaultSignatures`将*实现*编写一次,然后简单地编写`instance X Int; 实例X Double; 实例X整数; ...`. (3认同)