haskell - syntax in functions - case expressions

本文探讨了Haskell语言中Case表达式的使用方法及其作为模式匹配的灵活性。通过实例介绍了如何利用Case表达式进行模式匹配,并展示了其在不同场景中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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."

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值