Explanation of numbers in Haskell

I would like a clear explanation of Num , Real , Integral , Integer , Int , Ratio , Rational , Double , Float .

+5
source share
2 answers

This answer basically assumes that you know the difference between types and types of classes. If this difference is vague for you, then clear your understanding there before reading further.

Num

Num is a class that includes all numeric types.

 :info Num 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 -- Defined in 'GHC.Num' instance Num Word -- Defined in 'GHC.Num' instance Num Integer -- Defined in 'GHC.Num' instance Num Int -- Defined in 'GHC.Num' instance Num Float -- Defined in 'GHC.Float' instance Num Double -- Defined in 'GHC.Float' 

Real

Also a type class that can be represented as a real value ( Rational type).

 :info Real class (Num a, Ord a) => Real a where toRational :: a -> Rational -- Defined in 'GHC.Real' instance Real Word -- Defined in 'GHC.Real' instance Real Integer -- Defined in 'GHC.Real' instance Real Int -- Defined in 'GHC.Real' instance Real Float -- Defined in 'GHC.Float' instance Real Double -- Defined in 'GHC.Float' 

Integral

A type class for integrals, you know ...,-2,-1,0,1,... Types such as Integer (aka big int), Int, Int64, etc., are instances.

 :info Integral class (Real a, Enum a) => Integral a where quot :: a -> a -> a rem :: a -> a -> a div :: a -> a -> a mod :: a -> a -> a quotRem :: a -> a -> (a, a) divMod :: a -> a -> (a, a) toInteger :: a -> Integer -- Defined in 'GHC.Real' instance Integral Word -- Defined in 'GHC.Real' instance Integral Integer -- Defined in 'GHC.Real' instance Integral Int -- Defined in 'GHC.Real' 

Integer

A type, not a type class, for example, is what we have talked about so far that can represent unlimited integers. Therefore, 2^3028 is a legal value.

Int

Fixed Width Integral. In the GHC compiler, this is 32 or 64 bits, depending on your architecture. Haskell guarantees that it will be at least 29 bits.

Ratio

This is a type constructor, so you can say something like Ratio Integer to get a type for the ratio of two integers (mathematically a/b ).

Rational

Well, rational is literally a ratio of two integers, understands the relationship, and you're good at:

 :i Rational type Rational = Ratio Integer 

Double

Type for double precision floating point values.

Float

Type for single precision floating point values.

+9
source

There is an interesting image in the Haskell documentation that shows the relationships between classes and instances of their types, covering most of the topics you mentioned:

classes.gif

Regarding Rational numbers :

For each Integral type t, there exists a type Ratio t of rational pairs with components of type t. A type name Rational is synonymous with Ratio Integer .

+1
source

All Articles