Vla*_*sky 4 haskell pattern-matching guard-clause
给定空字符串时,以下两个函数的行为有所不同:
guardMatch l@(x:xs)
| x == '-' = "negative " ++ xs
| otherwise = l
patternMatch ('-':xs) = "negative " ++ xs
patternMatch l = l
Run Code Online (Sandbox Code Playgroud)
这是我的输出:
*Main> guardMatch ""
"*** Exception: matching.hs:(1,1)-(3,20): Non-exhaustive patterns in function guardMatch
*Main> patternMatch ""
""
Run Code Online (Sandbox Code Playgroud)
问题:为什么'否则'关闭空接字符串?
gee*_*aur 13
的otherwise是该图案的范围内l@(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
Run Code Online (Sandbox Code Playgroud)
(实际上,我认为它if被翻译成case+守卫而不是相反.)