The Num class of haskell allows for quite general algebraic structures and looks like it's intended to be used to make rings. When speaking of a ring though, it's convenient to be able to explicitly mention its additional and multiplicative units - maybe Num.Zero and Num.One - is there such a thing to Num, another class that includes units or some other way that this is done?
If your instance of Num
is a ring, one expects fromInteger
to be a ring homomorphism and thus 0
and 1
will just work. This may not always hold. Num
predates typeclasses having algebraic laws be the norm. Also, unfortunetly, many instances of Num
are not rings (such as floating point numbers).
Num
is not really a ring structure, since it also has "other stuff" like abs
, signum
and the (hopefully) ring homomorphism fromInteger
. I tend to think of it as "probably ring-ish with some other stuff."
Example: the ring of Gaussian rationals
import Data.Ratio
import Data.Complex
type GaussianRational = Complex Rational
zero :: GaussianRational
zero = 0
one :: GaussianRational
one = 1
EDIT: Since Z is initial in Ring, the idea of using fromInteger
this way actually makes a lot of sense.
The entire algebra
package is devoted to these kinds of purposes. For instance, we have
class (Rig r, Rng r) => Ring r
and the supporting cast
class (Semiring r, Unital r, Monoidal r) => Rig r
class (Group r, Semiring r) => Rng r
class Multiplicative r => Unital r
class (Additive r, Abelian r, Multiplicative r) => Semiring r
class (LeftModule Integer r, RightModule Integer r, Monoidal r) => Group r
class (LeftModule Natural m, RightModule Natural m) => Monoidal m
class (Semiring r, Additive m) => RightModule r m
class (Semiring r, Additive m) => LeftModule r m
class Multiplicative r
class Additive r
class Additive r => Abelian r
which is at least one way to build up a ring. If you're doing highly general algebra then algebra
might be worth it, but most libraries just expect Num
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With