简体   繁体   English

存在量化类型无法在类型类上下文中推断

[英]Existentially quantified types Could not deduce in the typeclass context

{-# LANGUAGE ExistentialQuantification, DeriveDataTypeable #-}
import Data.Typeable;

data EnumBox = forall s. (Enum s, Show s) => EB s
           deriving Typeable

instance Show EnumBox where
  show (EB s) = "EB " ++ show s

This works. 这有效。 But if I want to add a instance of Class Enum for EnumBox likes: 但是,如果我想为EnumBox添加类Enum实例,请执行以下操作:

instance Enum EnumBox where
  succ (EB s) = succ s

It fails with the message: 它失败并显示以下消息:

Could not deduce (s ~ EnumBox)
from the context (Enum s, Show s)
  bound by a pattern with constructor
             EB :: forall s. (Enum s, Show s) => s -> EnumBox,
           in an equation for `succ'
  at typeclass.hs:11:9-12
  `s' is a rigid type variable bound by
      a pattern with constructor
        EB :: forall s. (Enum s, Show s) => s -> EnumBox,
      in an equation for `succ'
      at typeclass.hs:11:9
In the first argument of `succ', namely `s'
In the expression: succ s
In an equation for `succ': succ (EB s) = succ s

Why the first show can be deduced but the second succ cannot? 为什么第一个节目可以推断,但第二个节目不能?

You're only problem is that succ has the type 你唯一的问题是succ有这种类型

succ :: Enum a => a -> a

So you need 所以你需要

succ (EB s) = EB . succ $ s

Just boxing it up again. 再次装箱。

Also you'll probably want 你可能也想要

instance Enum EnumBox where
    toEnum = EB
    fromEnum (EB i) = fromEnum i

As this is the minimum definition of completeness, since 因为这是完整性的最低定义,因为

succ = toEnum . succ . fromEnum

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM