[Haskell] 1::Num a => a

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’

可见Num是一个type class,而数字1是定义在这个type class中的,具有多态性(Ad Hoc Polymorphism)。
因此,type class中不但可以定义函数,还可以定义值
(当然,函数只是一种具有函数类型的值罢了

例如:

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)实际上,func只是一个类型为(->) t t的值
(2)从这个角度来讲,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.

Haskell 2010 Language Report - P82

你可能感兴趣的:([Haskell] 1::Num a => a)