如下
bmiTell :: ( RealFloat a ) => a -> a -> String
bmiTell weight height
| weight / height ^ 2 <= 18.5 = "underweight"
| weight / height ^ 2 <= 25.0 = "normal"
| weight / height ^ 2 <= 30.0 = "fat"
| otherwise = "whale!"
这里我们重复同一个表达式三次,如果我们可以计算一次,将它绑定到一个变量,并使用变量而不是表达式,那将是理想的,如下
bmiTell :: ( RealFloat a ) => a -> a -> String
bmiTell weight height
| bmi <= skinny = "underweight"
| bmi <= normal = "normal"
| bmi <= fat = "fat"
| otherwise = "whale!"
where bmi = weight / height ^ 2
skinny = 18.5
normal = 25.0
fat = 30.0
- 将where关键字放在御林军之后(通常最好将其与其余竖条对其),然后定义几个变量。
- 这些变量在御林军上是可见的,这样就不用重复了,还提升了可读性
- 在函数的where部分中定义的变量只在该函数中可见
where部分可以使用模式,如下
initials :: String -> String -> String
initials firstName lastName = [f] ++ "." ++ [l]
where (f : _) = firstName
(l : _) = lastName
where部分可以定义函数,如下
calcBmis :: (RealFloat a) => [(a, a)] -> [a]
calcBmis xs = [bmi w h | (w, h) <- xs]
where bmi weight height = weight / height ^ 2
where部分可以嵌套
在where部分中创建一个函数,并定义一些辅助函数,然后在每个函数中定义其他辅助函数,这是非常常见的