haskell - 通配符模式匹配在 case 表达式中如何工作?
问题描述
我发现了一个奇怪的 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 ...
这样写是为了强调它的价值是无关紧要的。
推荐阅读
- spring-boot - JMS 连接在我们的 oracle 队列中不断“会话已关闭”
- excel - 更新 VBA Excel 插件的困境
- ios - 如何在 Phonegap 和 Cordova 构建的混合应用程序上测试调试(Cpu 和 FPS)使用情况
- batch-file - windows shell:从文件中提取命令并运行它们
- powershell - 根据公式自动批量重命名文件,包括使用 Powershell 的父文件夹名称
- html - 在 flexbox 列中并排设置两个 flex 项
- java - 我可以将 try-with-resources 与已创建的 InputStream 一起使用吗?
- design-patterns - 是否存在遍历树的实体的术语或设计模式
- nunit - NUnit 并行运行类
- python - AssertionError: Index is not unique on dataframe (Entity cust) using Featuretools