`

haskell - syntax in functions - case expressions

阅读更多

This is an advanced topic to the post haskell - syntax in functions , where we wil dicuss the the case expressions. 

 

By the name,  you might have figured out that the case expression is, well, expression, if it is an expression, then you can embedded the expression anywhere an expressoin is expected. 

 

an example of the case expression is as such .

describeList :: [a] -> String  
describeList xs = "The list is " ++ case xs of [] -> "empty."  
                                               [x] -> "a singleton list."   
                                               xs -> "a longer list."  

 
so, so with the case expression, Not only can we evaluate expressions based on the possible cases of the value of a variable, we can also do pattern matching.

 

the following will be dicsussed.

  • case expression in general 
  • case expression is an expression
  • patterns aligned to the same columnm with regards to case expressions
  • pattern matching in function definition is syntactic sugar for case expression.
-- let_in.hs
-- discuss the case expression in general
-- have I told you that the pattern-matching is syntactic sugar for case expression?

head' :: [a] -> a
head' [] = error "No head for empty list!"
head' (x:_) = x


-- rewrite with the case expression 
head'' :: [a] -> a
head'' xs = case xs of [] -> error "No head for empty list!"
                       (x: _) -> x

-- case expression of pattern -> result  
--                    pattern -> result  
--                    pattern -> result  
--                    ...  		       

-- case expression can be widely used.
-- pattern-matching on functino parameter only when you define functions
-- case exprssion can be used anywhere

describeList :: [a] -> String  
describeList xs = "The list is " ++ case xs of [] -> "empty."  
                                               [x] -> "a singleton list."   
                                               xs -> "a longer list."  
-- above can have "pattern-maching" in the middle of an expression
-- an equivalent one is like this:

describeList' :: [a] -> String
describeList' xs = "The list is " ++ what xs 
  where what [] = "empty."
        what [x] = "a singleton list."
        what xs = "a longer list."

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics