haskell笔记2
模式匹配
# haskell_test.hs length' :: [a] -> a length' [] = 0 length' (_:x) = 1 + length' x
as模式
xs@x:y:ys xs代表整个list x代表一部分 方便引用原值,而非分割的 capital :: String -> String capital "" = "empty" capital xs@(x:y) = "the first of " ++ xs ++ " is " ++ x;
guard
# bmi eg
bmiTell weight height
| weight / height ^ 2 <= 18.5 = "you are thin."
| weight / height ^ 2 <= 25 = "you are nomal."
| weight / height ^ 2 <= 30 = "you are fat."
| otherwise = "you are fat to die."
有重复。可改为
bmiTell weight height
| bmi <= thin = "you are thin."
| bmi <= nomal = "you are nomal."
| bmi <= fat = "you are fat."
| otherwise = "you are fat to die."
where bmi = weight / height ^ 2
thin = 18.5
nomal = 25
fat = 30
let
let (a,b) = (2,3) in a^2 + b
case 模式匹配的语法糖
head' :: [a] -> a head' [] = error "error" head' (x:_) = x 等价于 head' :: [a] -> a head' xs = case xs of [] -> error "error" (x:_) -> x