gpt4 book ai didi

haskell - 通配符模式匹配在 case 表达式中如何工作?

转载 作者:行者123 更新时间:2023-12-02 18:31:01 25 4
gpt4 key购买 nike

我想了解 example server code它使用 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
...

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

最佳答案

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 ... 来强调它的值(value)是无关紧要的。

关于haskell - 通配符模式匹配在 case 表达式中如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51274533/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com