# More on type classes and instances

• 本 Handout 备份于此处。（不保证与源文件同步）

1. 类型类 Ord 用于有序类型。
2. 用于数字类型的 Num 类型。

## The type Ordering and the typeclass Ord​

There is also a video on this section.

data  Ordering  =  LT | EQ | GT          deriving (Eq, Ord, Enum, Read, Show, Bounded)

Here, LT stands for less than, EQ stands for equal, and GT stands for greater than.

class  (Eq a) => Ord a  where    compare              :: a -> a -> Ordering    (<), (<=), (>=), (>) :: a -> a -> Bool    max, min             :: a -> a -> a        -- Minimal complete definition:        --      (<=) or compare        -- Using compare can be more efficient for complex types.    compare x y         | x == y    =  EQ         | x <= y    =  LT         | otherwise =  GT    x <= y           =  compare x y /= GT    x <  y           =  compare x y == LT    x >= y           =  compare x y /= LT    x >  y           =  compare x y == GT-- note that (min x y, max x y) = (x,y) or (y,x)    max x y         | x <= y    =  y         | otherwise =  x    min x y         | x <= y    =  x         | otherwise =  y

OrderingOrd 的定义之间似乎存在着一种循环性，因为每个人都提到了另一个。我们可以把这看作是一个相互递归的定义。

instance (Ord a) => Ord [a] where  compare [] []         = EQ  compare [] (_:_)      = LT  compare (_:_) []      = GT  compare (x:xs) (y:ys) = case compare x y of                              EQ    -> compare xs ys                              other -> other

1. 通过阅读代码，解释如何比较两个列表。
2. 运行一些列表间比较的例子来证实或反驳你的解释。

This video gives an explanation of the implementation of compare :: [a] -> [a] -> Ordering.

## The type class Num​

Prelude> 5 + 38Prelude> 3.14159 + 2.718285.85987

Prelude> :info Numclass 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 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'

Prelude> :type 1 :: Word1 :: Word :: Word

Prelude> :type (+) :: Integer -> Integer -> Integer(+) :: Integer -> Integer -> Integer  :: Integer -> Integer -> Integer

Prelude> :type (+) :: Char -> Char -> Char<interactive>:1:1: error:    • No instance for (Num Char) arising from a use of '+'    • In the expression: (+) :: Char -> Char -> Char

## 测试时间​

1. 我们详细研究了一个同时使用列表上的模式匹配和 case 表达式（模式匹配的一种更通用的形式）的函数。
2. 我们已经看到实例是如何从其他实例中自动派生出来的，使用的例子是 instance Ord a => Ord [a]
3. 我们看了一下用于数字类型的类型类 Num
4. 我们看到了如何使用类型注解来强制 Haskell 表达式具有特定的类型，例如，1 :: Word