是什么导致“无可辩驳的模式因模式而失败”,这是什么意思?

问题描述 投票:23回答:3

是什么

无可辩驳的模式因模式而失败

意思?什么情况会导致此运行时错误?

haskell pattern-matching runtime-error
3个回答
20
投票

好吧,我认为它意味着它所说的 - 一个模式不匹配但没有其他选择。这个例子:

但对于该计划:

g x = let Just y = f x in h y 

GHC报道:

Main: M1.hs:9:11-22:
    Irrefutable pattern failed for pattern Data.Maybe.Just y 

指出失败的根源。

来自http://www.haskell.org/haskellwiki/Debugging

示例的要点是,如果f x返回Nothing,那么GHC无法为y赋值。


20
投票

考虑这个例子:

foo ~(Just x) = "hello"
main = putStrLn $ foo Nothing

这使用了无可辩驳的模式(~部分)。无可辩驳的模式总是“匹配”,所以这打印hello

foo ~(Just x) = x
main = putStrLn $ foo Nothing

现在,模式仍然匹配,但是当我们尝试使用x时它实际上并不存在,我们得到了一个无可辩驳的模式匹配错误:

Irr.hs: /tmp/Irr.hs:2:1-17: Irrefutable pattern failed for pattern (Data.Maybe.Just x)

这与没有匹配模式时得到的错误略有不同:

foo (Just x) = x
main = putStrLn $ foo Nothing

这输出

Irr.hs: /tmp/Irr.hs:2:1-16: Non-exhaustive patterns in function foo

当然,这是一个有点人为的例子。更可能的解释是它来自let绑定中的模式,as chrisdb suggested


8
投票

要添加其他人所说的内容,如果您正在断开小于您想要的列表,那么从技术上讲,您可以获得它。例如(在GHCi中):

Prelude> let l = [1,2,3]
Prelude> let (x:x1:xs) = l
Prelude> x
1

工作正常,但如果你这样做:

Prelude> let l2 = [1]
Prelude> let (x:x1:xs) = l2
Prelude> x
*** Exception: <interactive>:294:5-18: Irrefutable pattern failed for pattern (x : x1 : xs)
© www.soinside.com 2019 - 2024. All rights reserved.