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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章