Skip to content

Num

I've mentioned Num as the class of number types before. Here is its definition:

GHCi
type Num :: * -> Constraint
class Num a where
  (+) :: a -> a -> a
  (-) :: a -> a -> a
  (*) :: a -> a -> a
  negate :: a -> a
  abs :: a -> a
  signum :: a -> a
  fromInteger :: Integer -> a
  {-# MINIMAL (+), (*), abs, signum, fromInteger, (negate | (-)) #-}
    -- Defined in ‘GHC.Num’
[More omitted output]

To be an instance of Num, a type a needs to support addition, subtraction, multiplication, negation, taking the absolute value or sign, and conversion from the Integer type to the type a. This last condition is necessary because we want to be able to use number literals, such as 0, 1 or 523, for any type a that is a number type. The Haskell compiler parses these literals as Integers, and fromInteger allows us to convert these Integers into any number type a.

Note the omission of division from the list of arithmetic operations that a number type must support. That's a consequence of Haskell having two different division operations for integral types, div, and for fractional types, (/). Since a number type can be an integral type or a fractional type, we cannot require every number type to implement div or (/). For that, we need subclasses of Num, discussed next.