2013-09-01 18 views
3
{-# 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喜欢:存在量化类型无法在类型上下文中推导

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 

为什么首秀可以推断出,但第二SUCC不能?

+4

好像你忘了运用'EB'为'SUCC s'。 – Vitus

+0

你说得对。我想念包装。 – highfly22

回答

2

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

谢谢。这就是我要的。 – highfly22

+0

只有一个例外。在toEnum函数中,它丢失了由EnumBox包装的类型。在这种情况下,EnEn。 fromEnum(EB'a')/ = EB'a' – highfly22

相关问题