为什么标识函数有时会改变模式是否穷举?

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

考虑本GHCi会议:

$ ghci
GHCi, version 8.6.5: http://www.haskell.org/ghc/  :? for help
Prelude> :set -Wincomplete-patterns -Wincomplete-uni-patterns
Prelude> foo t | (_, _) <- t = "Foo"
Prelude> bar t | (_, _) <- id t = "Foo"
Prelude> baz x | Just _ <- x = "Yes" | Nothing <- x = "No"
Prelude> qux x | Just _ <- id x = "Yes" | Nothing <- id x = "No"

<interactive>:3:1: warning: [-Wincomplete-patterns]
    Pattern match(es) are non-exhaustive
    In an equation for ‘qux’: Patterns not matched: _
Prelude>

为什么GHC认为qux不完整?我们真的比id x更了解x吗?为什么bar也不会因为与qux相同的原因而被认为是不完整的?

haskell pattern-matching compiler-warnings
1个回答
1
投票

看起来像是GHC在简化之前对样式进行完整性检查。它根本没有考虑id的定义。它所看到的只是检查两个不同的表达式,这两个表达式都可能失败。因为表达式是不同的,所以GHC并不假定它们之间有任何关系。

我会说这可能是正确的做法。首先进行简化会带来更多的复杂性,而且我不确定您在实际代码中会获得什么好处。如果您希望GHC知道您要彻底检查表达式的结果模式,请检查相同的表达式。

关于为什么在bar中没有收到该错误,这是因为只有一对构造函数。您正在匹配id t的所有可能输出,即使它是一个计算表达式也是如此。没有其他匹配的构造函数。

© www.soinside.com 2019 - 2024. All rights reserved.