模式匹配
当调用函数lucky 7时会返回test 7,当调用luck参数不为7时会输出sorry
lucky 7 = "test 7" lucky x = "sorry"
仿head函数实现,如果List参数长度为0则,调用error发出一个异常,如果有元素则用模式匹配,多个参数的匹配要用括号()。
head' [] = error "error" head' (x: _) = x
实现自己的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则执行,如果没有任何guard为True,则运行异常,所以otherwise指定了任何情况,otherwise为True
bmiTell weight height | weight / height ^ 2 <= 18.5 = "<= 18.5" | weight / height ^ 2 <= 25 = "<= 25" | otherwise = "otherwise"
max'函数
max' a b | a > b = a | otherwise = b
我们可以定义函数的时候使用中缀形式定义和调用,通过``
Paste_Image.pngwhere
通过where能定义多个名字和函数,通过where,简化了重复的部分。
bmiTell weight height | bmi <= 18.5 = "<= 18.5" | bmi <= 25 = "<= 25" | otherwise = "otherwise" where bmi = weight / height ^ 2
关键字let
let是个表达式,在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也可以定义局部函数,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"
网友评论