首页 > 解决方案 > 通配符模式匹配在 case 表达式中如何工作?

问题描述

我想了解一个使用WebSocket库的示例服务器代码。

我发现了一个奇怪的 case 表达式,我无法理解:

case msg of
    _   | not (prefix `T.isPrefixOf` msg) ->
            WS.sendTextData conn ("Wrong announcement" :: Text)

        | any ($ fst client)
            [T.null, T.any isPunctuation, T.any isSpace] ->
                WS.sendTextData conn ("Name cannot " `mappend`
                    "contain punctuation or whitespace, and " `mappend`
                    "cannot be empty" :: Text)

        | clientExists client clients ->
            WS.sendTextData conn ("User already exists" :: Text)

        | otherwise -> flip finally disconnect $ do

        -- ...

外卡在这里是什么意思?case 表达式的语法是这样的:

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

为什么是_必要的,为什么作者能够在其中使用警卫?

标签: haskell

解决方案


case irrelevant of
   _ | condition1 -> e1
     | condition2 -> e2
     ...
     | otherwise  -> eO

是一种编写链的奇特方式if then else

if condition1 
then e1
else if condition2
then e2
...
else eO

irrelevant表达无关紧要。它的值与 匹配_,它总是成功并丢弃该值。

您的代码混淆使用case msg of ...msg被忽略。经常有人case () of ...这样写是为了强调它的价值是无关紧要的。


推荐阅读