简体   繁体   English

为什么 Haskell 类型的“派生积分”需要“派生枚举”?

[英]Why does a Haskell type "deriving Integral" need to be "deriving Enum"?

I've recently been trying to "learn me a Haskell," and I'd like to create a new type to represent an integer state, without just using a raw Integer (for type safety and code clarity).我最近一直在尝试“学习 Haskell”,我想创建一个新类型来表示 integer state,而不仅仅是使用原始 Integer(为了类型安全和代码清晰)。 Specifically, the following code compiles:具体来说,编译以下代码:

newtype AuxState = AuxState Integer
  deriving (Eq, Ord, Num, Integral, Real, Enum)

However, since there are an infinite number of states in my application, I have no interest in converting this state into an Enum.但是,由于我的应用程序中有无数个状态,所以我没有兴趣将这个 state 转换为枚举。 However, if I try to remove the deriving (Enum) statement so it's just deriving (Eq, Ord, Num, Integral, Real) , the compiler complains:但是,如果我尝试删除deriving (Enum)语句,使其只是deriving (Eq, Ord, Num, Integral, Real) ,编译器会抱怨:

No instance for (Enum AuxState)
  arising from the 'deriving' clause of a data type declaration
Possible fix:
  add an instance declaration for (Enum AuxState)
  or use a standalone 'deriving instance' declaration,
       so you can specify the instance context yourself
When deriving the instance for (Integral AuxState)

I find it hard to believe that Haskell forces a type in the Integral class to also be in the Enum class;我发现很难相信 Haskell 会强制 Integral class 中的类型也出现在 Enum class 中; shouldn't it just be the other way around?不应该反过来吗? Is there a reason for this, or am I doing/understanding something wrong?这是有原因的,还是我做错了/理解错了什么?

All Integral are necessarily Enum because the foundations of Integral math are the succ and pred operations.所有Integral都必然是Enum ,因为Integral数学的基础是succpred操作。 (Technically Enum is standing in for a proper type hierarchy where an Integral type is a mathematical semigroup, I think.) The other way around seems even more wrong: you mean that every Enum should be Integral ? (从技术上讲, Enum代表一个适当的类型层次结构,其中Integral类型是数学半群,我认为。)反过来似乎更错误:你的意思是每个Enum都应该是Integral Does this include random ADTs like这是否包括像这样的随机 ADT

data Foo = A | B | C | D | E | F | G deriving (Enum)

?

(Every Enum should be isomorphic to a subset of Integral , surely, but that actually suggests it going the other direction: Integral can represent any Enum but not vice versa, so Integral is kind of the ur- Enum .) (当然,每个Enum都应该同构于Integral的一个子集,但这实际上表明它朝另一个方向发展: Integral可以表示任何Enum ,但反之亦然,因此Integral是一种 ur- Enum 。)

The technical reason is because is because Integral is defined in Prelude as follows:技术上的原因是因为IntegralPrelude中是这样定义的:

class (Real a, Enum a) => Integral a where
   ...

The mathematical reason is that every integral type is enumerable but not vice versa.数学原因是每个整数类型都是可枚举的,但反之则不然。 Think about rational numbers for example.以有理数为例。 Note, that Enum does not imply finite enumeration as is shown by Integer .请注意,枚举并不意味着有限枚举,如Integer所示。

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

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