算術
數字型別層次結構
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
級模型..實數。它需要 Num
和 Ord
,因此它模擬有序數值域。作為一個反例,複數不是有序欄位(即它們不具有自然排序關係):
λ> :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 欄位(稍後顯示)。