我可以得到 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
,那将毫无意义。陈述。如果您希望所有模式的变量都在范围内,则必须在开始模式匹配之前绑定(bind)这些变量。为您的函数定义一个方程,并在其中定义变量,或者使用
let
或与 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
关于haskell - 如何跨模式匹配执行 where 子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62926701/