haskell 笔记3

1 .pattern matching

pattern matching example

luckly :: (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 statement

a 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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值