haskell - 如何跨模式匹配执行 where 子句
问题描述
我可以让一个where
子句在模式匹配case
语句中起作用:
updateHung :: Text -> Maybe Char -> Int
updateHung word got =
let x = case got of
Just l
| elem l . unpack $ word -> pass
| otherwise -> strike
Nothing -> pass
where
strike = 1
pass = 0
in x
但是当我尝试使用 multipart 函数做同样的事情时它不起作用:
updateHung :: Text -> Maybe Char -> Int
updateHung word (Just l)
| elem l . unpack $ word = pass
| otherwise = strike
updateHung word Nothing = pass
where
strike = 1
pass = 0
有什么方法可以让它工作吗?
解决方案
在工作版本中,您的where
子句被误导性缩进。您已将其缩进,就好像它附加到case
语句中一样,但实际上它附加到 , 的定义中x
,并且会更清楚地缩进为
updateHung :: Text -> Maybe Char -> Int
updateHung word got =
let x = case got of
Just l
| elem l . unpack $ word -> pass
| otherwise -> strike
Nothing -> pass
where
strike = 1
pass = 0
in x
一个where
子句的范围总是限定为单个模式,跨越该模式的所有守卫。这非常重要,因为这允许它使用由模式引入的变量。例如,l
在 的定义中使用它可能对您有用,但如果您能以某种方式将其范围限定为整个语句pass
,那将毫无意义。case
如果您希望所有模式的变量都在范围内,则必须在开始模式匹配之前绑定这些变量。为您的函数定义一个方程,并在其中定义变量,无论是 withlet
还是 with where
,然后在case
所有参数的元组上执行其余的逻辑,或者只是您关心的参数:
updateHung :: a -> Maybe Char -> Int
updateHung word got =
let strike = 1
pass = 0
in case got of
Just l
| elem l . unpack $ word -> pass
| otherwise -> strike
Nothing -> pass
或者
updateHung :: Text -> Maybe Char -> Int
updateHung word got =
case got of
Just l
| elem l . unpack $ word -> pass
| otherwise -> strike
Nothing -> pass
where strike = 1
pass = 0
推荐阅读
- coq - 寻找一些匹配技巧或车队模式
- oop - ColdFusion 2018 Bean-DAO-Manager OOP 逻辑错误
- python - NLTK - 停用词,散列列表
- powershell - 多次创建用户
- scala - 是否可以覆盖包含在正在扩展的特征中的隐式对象?
- python - 熊猫数据框问题。创建列,其中一个行单元格获取另一个行单元格的值
- html - 创建 svg wave 后绘制的意外线
- html - 如何在响应式复选框汉堡菜单上居中菜单
- typescript - typescript - 类验证器 - 基于不同类型进行验证
- .net - 使用带有身份和 JWT 令牌的 ef 核心添加 Swagger 授权