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

标签 haskell typeclass existential-type

{-# 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 添加一个 Class 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

为什么第一个show可以推导出第二个succ不行?

最佳答案

你唯一的问题是 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

关于haskell - 存在量化类型无法在类型类上下文中推断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18559496/

相关文章:

scala - ADT 的类型类实例的通用派生

haskell - 存在类型。为异构 map 编写类的实例

haskell - 在 Haskell 中使用 Dynamic/fromDynamic 时是否可以恢复约束?

haskell - 如何在 Haskell 的列表中的每个元素上应用一个函数?

typeclass - 为什么定义 Choice 实例失败且值未知?

haskell - 没有存在类型的异构索引结构?

haskell - 强制性和存在主义

haskell - 如何将 Repa 数组折叠成任意值?

Haskell:为什么用户定义的枚举的算术序列中需要额外的空间?

haskell - 用于广义多参数函数提升的类型类技巧