Haskell中的非穷尽模式匹配 [英] Non-exhaustive pattern matching in Haskell
问题描述
我正在学习Haskell,想编写一个简单的程序,将每个字符串中的每个字母重复两次.
I am learning Haskell and wanted to write a simple program which just repeats each letter in a string twice.
我想到了这个
repl :: String -> String
repl " " = " "
repl (x:xs) = x:x:repl xs
编译时,我没有收到任何警告,但是当我执行repl "abcd"
时发生了运行时错误:
When compiling, I didnt get any warning but a run-time error occurred when I did repl "abcd"
:
"abcd ***:例外:repl.hs:(2,1)-(3,23):函数repl中的非穷举模式
"abcd*** Exception: repl.hs:(2,1)-(3,23): Non-exhaustive patterns in function repl
为什么编译器从不报告此问题,为什么当有很多语言(如OCaml)在编译时明确报告此问题时,为什么它在Haskell中被忽略?
Why did the compiler never report this and why is it ignored in Haskell when there are many languages like OCaml which clearly report this at compile time?
推荐答案
模式匹配警告默认情况下处于关闭状态.您可以使用-fwarn-incomplete-patterns
启用它,也可以使用-W
和-Wall
将其作为更大的警告包的一部分.
The pattern match warning is turned off by default. You can turn it on with the -fwarn-incomplete-patterns
or as part of a larger bundle of warnings with -W
and -Wall
.
您可以从ghci
执行此操作:
Prelude> :set -W
您还可以在编译或将其作为编译指示包含在模块顶部时,将标志传递给ghc
:
You can also pass the flag to ghc
when you compile or include it as a pragma on top of your module:
{-# OPTIONS_GHC -fwarn-incomplete-patterns #-}
对于您的特定程序,它应发出以下警告:
For your specific program, it should give the following warning:
/home/tjelvis/Documents/so/incomplete-patterns.hs:2:1: Warning:
Pattern match(es) are non-exhaustive
In an equation for ‘repl’: Patterns not matched: []
这篇关于Haskell中的非穷尽模式匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!