haskell 笔记3
2018-02-04 14:54
232 查看
1 .pattern matching
pattern matching exampleluckly :: (Integral a)=>a->String luckly 7 = "you are luckly" luckly x = "nonono"
how to match a list
match_list :: [a] -> String match_list []= "error"//[] match_list (x,[]) = "one element"//[1] match_list (x,_) = "more than one element"//[1,2] //use _ to represent variable that doesn't matter
usage of @
a easy way to keep a reference to a whole list while you break a list into several parts
capital :: String -> String capital "" = "Empty string, whoops!" capital all@(x:xs) = "The first letter of " ++ all ++ " is " ++ [x]
2 guard
a little like if else statementa simple example bmiTell :: (RealFloat a)=>a->String//类型申明 ,可以省略 bmiTell bmi //申明参数 | bmi<=20 = "you are underweight" | bmi<=25 = "you are normal" | bmi<=30 = "you need to lose some weight" | otherwise = "wooooow" //类似与else语句,如果没有,可能引起无法匹配
use where to write a simple guard(more argument involved)
bmiTell :: (RealFloat a)=>a->String//类型申明 ,可以省略 bmiTell height weight //申明参数 | bmi<=20 = "you are underweight" | bmi<=25 = "you are normal" | bmi<=30 = "you need to lose some weight" | otherwise = "wooooow" //类似与else语句,如果没有,可能引起无法匹配 where bmi = height/weight
you can define more argument in where statement
where bmi = height/weight^2 fat = 25 skinny = 18
now let’s see let binding
func x y = let top_area = x*y bottom_area = x*y^2 in top_area+bottom_area //how can you write a similar function in where fun x y = top_area + bottom_area where (top_area,bottom_area) = (x*y,x*y^2)
the difference between let binding and where binding
The difference is that let bindings are expressions themselves. where bindings are just syntactic constructs. Remember when we did the if statement and it was explained that an if else statement is an expression and you can cram it in almost anywhere?
case expression
usage case expression of pattern -> result pattern -> result pattern -> result ......
blahblah :: (Num a)=>[a]->a blahblah x = case x++[1] of [] ->error"hhh" (x,_)->x blahblah [] >> 1
pattern matching is just sugar syntax for case expression
相关文章推荐
- Haskell笔记(二)
- Haskell语言学习笔记(41)Parsec(1)
- Haskell语言学习笔记(48)Data.Tuple
- Haskell 笔记(三)类型系统
- Haskell语言学习笔记(27)Endo, Dual, Foldable
- Haskell 学习笔记 1 --环境搭建与类型系统(Haskell Tutorial 1--Getting start with Haskell)
- Haskell语言学习笔记(8)Monoid
- Haskell 笔记 ①
- Haskell学习笔记 --- GHCi中如何敲入多行代码
- Haskell笔记(一)
- Haskell语言学习笔记(42)Bifunctor
- Haskell语言学习笔记(49)ByteString Text
- haskell笔记二:foldl与foldr的效率(惰性计算与尾递归)
- programming in haskell 读书笔记1
- 【笔记】Haskell
- Haskell语言学习笔记(43)Parsec(2)
- Haskell语言学习笔记(50)Extra
- Haskell学习笔记 --- 基础语法篇一
- haskell学习笔记(8)-haskell的类型系统
- Haskell语言学习笔记(44)Lens(2)