【问题标题】:Existentially quantified types Could not deduce in the typeclass context存在量化类型无法在类型类上下文中推断
【发布时间】:2013-09-01 14:43:19
【问题描述】:
{-# 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

这行得通。 但是如果我想为 EnumBox 添加一个 Enum 类的实例,喜欢:

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

失败并显示消息:

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

为什么第一个节目可以推断出第二个成功却不能?

【问题讨论】:

  • 您好像忘记将EB 应用到succ s
  • 你是对的。我想念包装纸。

标签: haskell typeclass existential-type


【解决方案1】:

你唯一的问题是 succ 有类型

succ :: Enum a => a -> a

所以你需要

succ (EB s) = EB . succ $ s

只是再次装箱。

你也可能想要

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

因为这是完整性的最低定义,因为

succ = toEnum . succ . fromEnum

【讨论】:

  • 谢谢。这就是我想要的。
  • 只有一个例外。在 toEnum 函数中,它丢失了 EnumBox 包裹的类型。在这种情况下, toEnum 。 fromEnum (EB 'a') /= EB 'a'
猜你喜欢
  • 1970-01-01
  • 2019-04-05
  • 1970-01-01
  • 2018-11-08
  • 1970-01-01
  • 1970-01-01
  • 2023-03-08
  • 2015-08-28
  • 1970-01-01
相关资源
最近更新 更多