haskell - 中缀模式匹配
问题描述
在 Haskell 中编程时有时会遇到一个问题,有时我想将模式与值匹配,但我只对值是否与模式匹配的真假信息感兴趣(例如,特定的数据类型构造函数)。例如:
data Color =
RGB Int Int Int
| Greyscale Int
toHex :: Color -> String
toHex color =
if isGreyscale color then something
else somethingElse
where
isGreyscale :: Color -> Bool
isGreyscale (Greyscale _) = True
isGreyscale _ = False
而我想在不创建不必要的辅助功能的情况下进行模式匹配,类似于:
toHex :: Color -> String
toHex color =
if (color ~~ (Greyscale _)) then something
else somethingElse
是否有特定的语法允许类似于上面的示例?或者也许在这种情况下会派上用场的成语?
解决方案
我不相信存在(或可能存在)中缀运算符,因为模式不是值;这是语法。
你正在寻找一个case
表达
toHex :: Color -> String
toHex color = case color of
Greyscale _ -> something
otherwise -> somethingElse
尽管您通常会将其写为
toHex :: Color -> String
toHex (Greyscale _) = something
toHex _ = somethingElse
这基本上对上面的代码进行了取消。
GHC中还有一个LambdaCase
扩展,它允许您编写以下内容,消除其他不必要的变量color
。
{-# LANGUAGE LambdaCase #-}
toHex :: Color -> String
toHex = \case
Greyscale _ -> something
otherwise -> somethingElse
推荐阅读
- r - 使用来自文本文件的信息的正态概率图
- json - 将 ffprobe json 元数据文件导入视频文件
- python - 从数组中删除出现超过 k 次的元素
- r - 转换多个csv。将文件转换为具有 R 中原始名称的多个矩阵
- ruby-on-rails - 如何将我与 Neo4j 的连接指定为 K8s 中的领导角色
- javascript - 超级表达式必须为空或函数??反应
- c++ - 在for循环中生成线程
- ios - EXC_BAD_ACCESS (SIGILL) 使用自动布局时崩溃?
- dart - 如何在 Angular Dart 2 中编写自定义模式验证器
- javascript - Javascript:在 var declare 中使用条件