Tuples

和 Python 的 Tuple 很类似,Haskell 在 Tuple 上定义了一些有用的函数

1
2
3
4
5
6
7
8
-- std::pair.first
fst :: (a, b) -> a
-- std::pair.second
snd :: (a, b) -> b

zip :: [a] -> [b] -> [(a, b)] -- two lists to list of pairs
unzip :: [(a, b)] -> ([a], [b]) -- list of pairs to pair of lists
partition :: (a -> Bool) -> [a] -> ([a], [a]) -- elements that satisfy and don't satisfy a predicate

tuple 上也可以进行 pattern matching

1
2
swap :: (a,b) -> (b,a)
swap (x,y) = (y,x)

Folding

什么是 folding? 给定一个列表 LL、函数 ff 和初始值 aa,将一整个列表不断应用 af(Li,a)a\gets f(L_i, a) 计算出一个值。

1
2
3
4
-- foldr, 类似于求数组的和
foldr :: (a -> b -> b) -> b -> [a] -> b
foldr f y [] = y
foldr f y (x:xs) = f x (foldr f y xs)

Type Classes

1
(==) :: (Eq a) => a -> a -> Bool

For all types a that belong to the class Eq, this is a function of type a -> a -> Bool. That is, if the type a is a member of the class Eq, you can give two values of type a to == and get a Bool result.