模式匹配
當(dāng)調(diào)用函數(shù)lucky 7時會返回test 7糙申,當(dāng)調(diào)用luck參數(shù)不為7時會輸出sorry
lucky 7 = "test 7" lucky x = "sorry"
仿head函數(shù)實現(xiàn),如果List參數(shù)長度為0則妓灌,調(diào)用error發(fā)出一個異常文搂,如果有元素則用模式匹配冒掌,多個參數(shù)的匹配要用括號()九昧。
head' [] = error "error" head' (x: _) = x
實現(xiàn)自己的length,如果List為空返回0狸棍,如果不是扁眯,則遞歸求長度
length' [] = 0 length' (_: xs) = 1 + length' xs
as模式
capital "" = "empty" capital all@(x: xs) = "The first letter of " ++ all ++ " is " ++ [x]
guard
|符號后面可以看成是guard的條件痊剖,如果為True則執(zhí)行取视,如果沒有任何guard為True召衔,則運行異常骑疆,所以otherwise指定了任何情況鲫凶,otherwise為True
bmiTell weight height | weight / height ^ 2 <= 18.5 = "<= 18.5" | weight / height ^ 2 <= 25 = "<= 25" | otherwise = "otherwise"
max'函數(shù)
max' a b | a > b = a | otherwise = b
我們可以定義函數(shù)的時候使用中綴形式定義和調(diào)用寸爆,通過``
where
通過where能定義多個名字和函數(shù),通過where礁鲁,簡化了重復(fù)的部分。
bmiTell weight height | bmi <= 18.5 = "<= 18.5" | bmi <= 25 = "<= 25" | otherwise = "otherwise" where bmi = weight / height ^ 2
關(guān)鍵字let
let是個表達(dá)式赁豆,在Haskell中if也是個表示式仅醇,它會有返回值
cylinder r h = let sideArea = 2 * pi * r * h; topArea = pi * r ^ 2 in sideArea + 2 * topArea
格式let [binding] in [expression]
let中得綁定的名字只對in可見。let也可以定義局部函數(shù)魔种,in部分可以省略析二。其作用域則是ghci交互過程中
let square x = x * x in (square 4) 輸出16
模式匹配的法語糖case
describeList xs = "This list is " ++ case xs of [] -> "empty" [x] -> "a singleton list" xs -> "a longer list"