当给定一个空字符串时,以下两个函数的行为有所不同:

guardMatch l@(x:xs)
    | x == '-'        = "negative " ++ xs
    | otherwise       = l

patternMatch ('-':xs) = "negative " ++ xs
patternMatch l        = l

这是我的输出:
*Main> guardMatch ""
"*** Exception: matching.hs:(1,1)-(3,20): Non-exhaustive patterns in function guardMatch

*Main> patternMatch ""
""

问题:为什么“否则”关闭不捕获空字符串?

最佳答案

otherwisel@(x:xs)模式的范围内,该模式只能匹配非空字符串。可能会有所帮助,以了解这(有效地)在内部转换为什么:

guardMatch   l = case l of
                   (x  :xs) -> if x == '-' then "negative " ++ xs else l
patternMatch l = case l of
                   ('-':xs) ->                  "negative " ++ xs
                   _        ->                                         l

(实际上,我认为if转换为case +保护器,而不是相反的方式。)

关于haskell - 模式与守卫 : otherwise does not match?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6585427/

10-14 04:17