Variables

Variables: Local Definition

使用 let ... in 语法,或者 where 语法。where 后置变量定义,let ... in 则是前置。

示例:

1
2
3
4
5
6
7
8
9
10
11
solve :: Int -> Int -> [Int] -> String
solve n m doors = do
case indices of
[] -> "YES"
_ -> case end - start + 1 of
x | x <= m -> "YES"
_ -> "NO"
where -- 这里就是 local definition 定义的局部变量
indices = elemIndices 1 doors
end = last indices
start = head indices

Pattern Matching

Pattern Matching

定义函数的时候,可以根据参数的不同,触发不同分支。

1
2
3
4
5
greet :: String -> String -> String
greet "Finland" name = "Hei, " ++ name
greet "Italy" name = "Ciao, " ++ name
greet "England" name = "How do you do, " ++ name
greet _ name = "Hello, " ++ name

Guards

Condition Guards

和 Pattern Matching 类似,用 Condition 代替具体的值进行 Matching.

示例:

1
2
3
4
5
6
7
describe :: Int -> String
describe n
| n == 2 = "Two"
| even n = "Even"
| n == 3 = "Three"
| n > 100 = "Big!!"
| otherwise = "The number " ++ show n

当然,Guards 和 Pattern Matching 也可以一起用。

1
2
3
4
5
6
7
8
9
10
guessAge :: String -> Int -> String
guessAge "Griselda" age
| age < 47 = "Too low!"
| age > 47 = "Too high!"
| otherwise = "Correct!"
guessAge "Hansel" age
| age < 12 = "Too low!"
| age > 12 = "Too high!"
| otherwise = "Correct!"
guessAge name age = "Wrong name!"

case ... of

我觉得 case ... of 语法也算 Pattern Matching 的一部分

Recursion

  • Helper Function: arguments of the helper function are variables you update in your loop; Tail Recursion Optimization

Haskell programs often use the apostrophe to name helper functions and alternative versions of functions.

Haskell 常用数据结构

List / [a]

1
2
3
4
5
6
7
8
9
10
11
head :: [a] -> a            -- returns the first element
last :: [a] -> a -- returns the last element
tail :: [a] -> [a] -- returns everything except the first element
init :: [a] -> [a] -- returns everything except the last element
take :: Int -> [a] -> [a] -- returns the n first elements
drop :: Int -> [a] -> [a] -- returns everything except the n first elements
(++) :: [a] -> [a] -> [a] -- lists are catenated with the ++ operator
(!!) :: [a] -> Int -> a -- lists are indexed with the !! operator
reverse :: [a] -> [a] -- reverse a list
null :: [a] -> Bool -- is this list empty?
length :: [a] -> Int -- the length of a list

实用函数

  • show :: Any -> String: 将任何东西变成可以输出的字符串