软糖

Haskell 2 Type and Typeclass

Taking Notes from http://learnyouahaskell.com

Type

1
2
3
4
ghci> :t 'a'
'a' :: Char
ghci> :t (True, 'a')
(True, 'a') :: (Bool, Char)

Function Type

1
2
addThree :: Int -> Int -> Int -> Int
addThree x y z = x + y + z

Types

Int 有界的整数
Integer 无界的
Float 单精度的浮点数
Double 双精度的浮点数
Bool True False
Char
Tuple

Type Variables

a 是类型变量, type variable

1
2
3
4
ghci> :t head
head :: [a] -> a
ghci> :t fst
fst :: (a, b) -> a

Typeclasses

1
2
ghci> :t (==)
(==) :: (Eq a) => a -> a -> Bool

Eq

判断相等性的接口
elem :: (Eq a) => a -> [a] -> Bool

Ord

包含可比较大小的类型. Ord 包中包含了<, >, <=, >= 和 compare 函数.
Compare 返回 GT, LT, EQ

Show

Show 的成员为可用字符串表示的类型

1
2
3
4
ghci> show 5.334
"5.334"
ghci> show True
"True"

Read

read 函数可以将一个字符串转为 Read 的某成员类型

1
2
3
4
5
6
ghci> read "5" - 2
3
ghci> read "4"
< interactive >:1:0:
ghci> read "4" :: Int
5

Enum

Enum的成员都是连续的类型 – 也就是可枚举
Enum 包含的类型有:(), Bool, Char, Ordering, Int, Integer, Float 和 Double
succ (successer)函数和 pred (predecesor)函数

1
2
ghci> succ 'B'
'C'

Bounded

成员都有一个上限和下限

Num

表示数字的 Typeclass. Num 包含所有的数字:实数和整数
类型只有亲近 Show 和 Eq,才可以加入 Num

1
2
ghci> :t (*)
(*) :: (Num a) => a -> a -> a

Integral

Integral 仅包含整数,其中的成员类型有 Int 和 Integer

Floating

仅包含浮点类型:Float 和 Double

fromIntegral

它取一个整数做参数并回传一个更加通用的数字
fromIntegral :: (Num b, Integral a) => a -> b

1
fromIntegral (length [1,2,3,4]) + 3.2