gpt4 book ai didi

haskell - 如何让 GHC 对 do block 中的不完整模式绑定(bind)发出警告?

转载 作者:行者123 更新时间:2023-12-03 14:30:01 25 4
gpt4 key购买 nike

以下 Haskell 程序已损坏,因为它执行了不完整的模式绑定(bind):

main = do
[x] <- pure ["foo", "bar"]
print x

如果您编译它,您将不会收到任何警告:
$ ghc -fwarn-incomplete-uni-patterns -o example example.hs
[1 of 1] Compiling Main ( example.hs, example.o )
Linking example ...

但如果你运行它,你会得到:
example: user error (Pattern match failure in do expression at example.hs:2:3-5)

我想以某种方式获得编译器警告。

从文档中,我会想到 -fwarn-incomplete-uni-patterns会这样做,因为 do阻止脱糖:

desugared = pure ["foo", "bar"] >>= \[x] -> print x

事实上,将其添加到示例文件中确实会产生警告:
$ ghc -fwarn-incomplete-uni-patterns -o example example.hs
[1 of 1] Compiling Main ( example.hs, example.o )

example.hs:1:37: Warning:
Pattern match(es) are non-exhaustive
In a lambda abstraction:
Patterns not matched:
[]
_ : (_ : _)

当我在 do 中执行相同操作时,如何得到类似的警告堵塞?
$ ghc --version
The Glorious Glasgow Haskell Compilation System, version 7.10.3

最佳答案

至于现在,为了避免由于这个怪癖而导致的错误,你唯一能做的就是避免使用 MonadFail 的单子(monad)。实例(在最近的 GHC 版本中,不完整的绑定(bind)模式会导致编译错误)。
There is already an issue for this .还有一个声明为这个解决方案辩护,指出它可能是完全可取的,因此不值得警告:

This is actually the right useful behavior. using things like

do
Just x <- xs
Just y <- ys
return (x,y)

will do the right thing, failing if xs or ysresults in Nothing. forinstance, in the list monad, it will create the cross product of thenon Nothing members of the two lists. a parse monad may backtrack andtry another route, the IO monad will create a useful (anddeterministic/catchable) exception pointing to the exact file and linenumber of the pattern match. The do notation is the only place inhaskell that allows us to hook into the pattern matching mechanism ofthe language in a general way.

关于haskell - 如何让 GHC 对 do block 中的不完整模式绑定(bind)发出警告?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37688094/

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