Why is there no Enum instance for Sum and Product?
If you import Data.Monoid
, you'll find that Sum
, Product
, All
, Any
are not instances Enum
, though Bool
, and instances Integral
do. Doesn't it make sense to provide an instance, say Enum a => Enum (Sum a)
? Is there some theoretical reason for this? I'm also grateful for the links that delve into the theory behind this.
source to share
Doesn't make sense to provide these instances? Not much. The purpose of these new types is that you can use a specific number type in a function that wants to deal with a generic instance Monoid
. The idea is that you Monoid
wrap up the arguments in the newtype constructor, use the -polymorphic function (which doesn't know that it just deals with wrapped numbers), and immediately unwraps the result. You do not do anything with the values of Sum
, Product
, Any
and so on, so you also do not need a copy Enum
.
The only reason you might need this is for a function limitation (Monoid a, Enum a) => ...
. But what an unlikely combination is that it is Monoid
a generic, high-level, "algebraic" class, whereas it Enum
is a fairly low-level, specific, set-ish class. If you require Enum
it means that you will deal more or less with the range of Int
s and assign your own meaning to the "zero element" and "combination of elements", so why would you also demand Monoid
?
But if you ever find yourself in this situation, you can simply define a new type locally and give it exactly what you want. At some point, this ad-hoc approach is more efficient than preemptively defining standard instances for every conceivable combination of type constraints, which in most cases will never be needed.
source to share