haskell - 如何跨模式匹配执行 where 子句

标签 haskell

我可以得到 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/

相关文章:

Haskell IO - hGetContents : illegal operation (handle is closed)

haskell - 为什么 Haskell 不能正确排序这些 IO 操作?

haskell - Monoid实例分辨率为 `Int -> Int -> Ordering`

haskell - 功能依赖与类型族

Haskell-如何在递归函数中跟踪计数器

haskell - Yesod 站点链接到本地​​主机 CSS 文件

haskell - 如何使用 hFileSize 在 Haskell 中获取文件大小

haskell - Haskell "understand"柯里化(Currying)函数定义吗?

haskell - 如何限制 WAI 中请求正文和 header 的大小?

haskell - 为什么这个 Haskell 代码不会终止?