3 ms·
> Isn't this why fixed, signed integer types don't have a Monoid instance? No. Integers (signed or unsigned, fixed or arbitrary-precision) don't have Monoid in
by a1369209993 4y ago
> Isn't this why fixed, signed integer types don't have a Monoid instance?
No. Integers (signed or unsigned, fixed or arbitrary-precision) don't have Monoid instances since Haskell requires a single class instance per type, and it's ambigous which instance should be the "canonical" one.
The types `Num a => Sum a` and `Num a => Product a` have Monoid instances, but it's not clear whether the "canonical" instance for a given integer type should have `(<>)` defined as `(+)` or `(*)`... or `min`, `max`, `and`, `or`, `xor`, `lcm`, `gcd`, or any of several dozen other monoidal operations.
Conversely, `[a]` doesn't really have any resonable monoidal operation other then `concat`, and most of the existing Monoid instances (most conspicuously Sum and Product above) are even more nothing-else-is-reasonable, if only because of their names.
- agentultra 4y agoAh ok that makes sense, and if you choose to use `Sum Int` you'd be technically implementing the Monoid abstraction for that type. In practice because the `Int` type is a signed, fixed-size integer it would break the laws for all integers. In that case it would still be a useful abstraction but you would have to be aware that your `Int` will wrap around for large values which kind of makes `Int` a poor choice. `Integer` would be better but is still somewhat finite because computers.
- a1369209993 4y ago> In practice because the `Int` type is a signed, fixed-size integer it would break the laws for all integers. No. `Sum Int` (unlike, pedantically, `Sum Integer` or `[a]`) is a valid (non-leaky-abstraction) monoid. It adds `Int`s, which is a monoidal operation that satisfies `(a<>b)<>c==a<>(b<>c)` for all (2^(3*MACHINE_BIT_WIDTH) distinct triplets (a,b,c) of) Ints, due to 2s-complement truncation on overflow. > your `Int` will wrap around for large values Yes, that's what `Int` means. > `Integer` will fail to terminate when adding sufficiently large values (in theory with a out of memory error, although in practice operations just get slower and slower until you abort them with ^C or a timeout), a property not shared by addition of `Int`.