I would like a clear explanation of Num
, Real
, Integral
, Integer
, Int
, Ratio
, Rational
, Double
, Float
.
This answer mostly assumes you know the difference between types and type classes. If that difference is hazy to you then clear up your understanding there before reading on.
Num
Num
is a typeclass 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 typeclass covering those types that can be represented as a real value (the 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 such as what we've talked about till now, that can represent unbounded integers. So 2^3028
is a legal value.
Int
A fixed-width integral. In the GHC compiler this is 32 or 64 bits depending on your architecture. The Haskell language only guarantees this will be at least 29 bits.
Ratio
This is a type constructor, so you would say something like Ratio Integer
to get a type for ratio's of two integers (mathematically a/b
).
Rational
Well a rational is literally a ratio of two integers, understand ratio and you're good:
:i Rational
type Rational = Ratio Integer
Double
A type for double precision floating point values.
Float
A type for single precision floating point values.