Prelude> :t 1
1 :: Num a => a
Prelude> :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
-- 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’
可見(jiàn)Num
是一個(gè)type class,而數(shù)字1
是定義在這個(gè)type class中的,具有多態(tài)性(Ad Hoc Polymorphism)。
因此,type class中不但可以定義函數(shù),還可以定義值
(當(dāng)然,函數(shù)只是一種具有函數(shù)類(lèi)型的值罷了
例如:
class TypeClassWithValueAndFunc t where
value :: t
func :: t -> t
Prelude> :t value
value :: TypeClassWithValueAndFunc t => t
Prelude> :t func
func :: TypeClassWithValueAndFunc t => t -> t
注:
(1)實(shí)際上,func
只是一個(gè)類(lèi)型為(->) t t
的值
(2)從這個(gè)角度來(lái)講,type class與OOP中的interface是有不同的,type class不一定是“操作”的集合,而是一些“值”的集合
6.4.1 Numeric Literals
The syntax of numeric literals is given in Section 2.5. An integer literal represents the application of the function fromInteger
to the appropriate value of type Integer. Similarly, a floating literal stands for an application of fromRational
to a value of type Rational
(that is, Ratio Integer
). Given the typings:
fromInteger :: (Num a) => Integer -> a
fromRational :: (Fractional a) => Rational -> a
integer and floating literals have the typings (Num a) => a
and (Fractional a) => a
, respectively. Numeric literals are defined in this indirect way so that they may be interpreted as values of any appropriate numeric type. See Section 4.3.4 for a discussion of overloading ambiguity.