gpt4 book ai didi

haskell - 模式与守卫 : otherwise does not match?

转载 作者:行者123 更新时间:2023-12-02 02:49:17 25 4
gpt4 key购买 nike

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

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 ""
""

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

最佳答案

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

(实际上,我认为 if 被翻译成 case + 守卫而不是相反。)

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com