Local Definition

可以定义临时变量

where 语法
1
2
3
4
circleArea :: Double -> Double
circleArea r = pi * rsquare
where pi = 3.1415926
rsquare = r * r
let ... in 语法
1
2
3
circleArea r = let pi = 3.1415926
square x = x * x
in pi * square r

流程控制

if-then-else

1
2
3
4
5
6
login user password = 
if user == "unicorn73"
then if password == "f4bulous!"
then "unicorn73 logged in"
else "wrong password"
else "unknown user"

Pattern Matching

PM in Function Definition

使用 _ 下划线作为 default\tt{default} 通配

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

Conditional Definition (Guards)

可以使用更加复杂的条件进行函数定义

1
2
3
4
f x y z
| condition1 = something
| condition2 = other
| otherwise = somethingother

甚至可以和 Pattern Matching 搭配使用

Example
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 语法

更加方便的针对某个变量进行 routing

1
2
case <value> of <pattern> -> <expression>
<pattern> -> <expression>