算术

数字类型层次结构

Num 位于数字类型层次结构的根。它的特征操作和一些常见实例如下所示(默认加载 Prelude 加上 Data.Complex):

λ> :i 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
  {-# MINIMAL (+), (*), abs, signum, fromInteger, (negate | (-)) #-}
      -- Defined in ‘GHC.Num’
instance RealFloat a => Num (Complex a) -- Defined in ‘Data.Complex’
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’

我们已经看过 Fractional 类,它需要 Num 并介绍了 division``(/) 的概念和数字的倒数:

λ> :i Fractional
class Num a => Fractional a where
  (/) :: a -> a -> a
  recip::a -> a
  fromRational::Rational -> a
  {-# MINIMAL fromRational, (recip | (/)) #-}
      -- Defined in ‘GHC.Real’
instance RealFloat a => Fractional (Complex a) -- Defined in ‘Data.Complex’
instance Fractional Float -- Defined in ‘GHC.Float’
instance Fractional Double -- Defined in ‘GHC.Float’

Real 级模型..实数。它需要 NumOrd,因此它模拟有序数值域。作为一个反例,复数不是有序字段(即它们不具有自然排序关系):

λ> :i Real
class (Num a, Ord a) => Real a where
  toRational::a -> Rational
  {-# MINIMAL toRational #-}
      -- 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’

RealFrac 表示可以舍入的数字

λ> :i RealFrac
class (Real a, Fractional a) => RealFrac a where
  properFraction::Integral b => a -> (b, a)
  truncate::Integral b => a -> b
  round::Integral b => a -> b
  ceiling::Integral b => a -> b
  floor::Integral b => a -> b
  {-# MINIMAL properFraction #-}
      -- Defined in ‘GHC.Real’
instance RealFrac Float -- Defined in ‘GHC.Float’
instance RealFrac Double -- Defined in ‘GHC.Float’

Floating(暗示 Fractional)表示可能没有有限十进制扩展的常量和运算。

λ> :i Floating
class Fractional a => Floating a where
  pi::a
  exp::a -> a
  log::a -> a
  sqrt::a -> a
  (**) :: a -> a -> a
  logBase::a -> a -> a
  sin::a -> a
  cos::a -> a
  tan::a -> a
  asin::a -> a
  acos::a -> a
  atan::a -> a
  sinh::a -> a
  cosh::a -> a
  tanh::a -> a
  asinh::a -> a
  acosh::a -> a
  atanh::a -> a
  GHC.Float.log1p::a -> a
  GHC.Float.expm1 :: a -> a
  GHC.Float.log1pexp::a -> a
  GHC.Float.log1mexp::a -> a
  {-# MINIMAL pi, exp, log, sin, cos, asin, acos, atan, sinh, cosh,
              asinh, acosh, atanh #-}
      -- Defined in ‘GHC.Float’
instance RealFloat a => Floating (Complex a) -- Defined in ‘Data.Complex’
instance Floating Float -- Defined in ‘GHC.Float’
instance Floating Double -- Defined in ‘GHC.Float’

注意:虽然像 sqrt . negate::Floating a => a -> a 这样的表达式完全有效,但它们可能会返回 NaN(“not-a-number”),这可能不是预期的行为。在这种情况下,我们可能想要处理 Complex 字段(稍后显示)。